Support
Quality
Security
License
Reuse
kandi has reviewed interview and discovered the below as its top functions. This is intended to give you an instant insight into interview implemented functionality, and help decide if they suit your requirements.
Interview questions
How it is possible to cast parent to child in c#
if (p is Child child) {
child.DriveParentsToDespair();
}
How to resolve Custom Sort Runtime error 1004
Sub custom_sort()
Dim vCustom_Sort As Variant, rr As Long
vCustom_Sort = Array("Published", "Submitted", "Distributed", "Amending", "Awaiting Sign-off", "Materials Drafting", "Working Up", "Arranging Interview", "Sourcing Information/Images", "Confirmed", "Pitched", "On Hold", "Archive")
Application.AddCustomList ListArray:=vCustom_Sort
With ActiveWorkbook.Worksheets("Activity")
.Sort.SortFields.Clear
rr = .Cells(.Rows.Count, "B").End(xlUp).Row
With .Range("A2:L" & rr)
.Sort Key1:=.Columns(2), Order1:=xlAscending, DataOption1:=xlSortNormal, _
Orientation:=xlTopToBottom, Header:=xlYes, MatchCase:=False, _
OrderCustom:=Application.CustomListCount + 1
End With
.Sort.SortFields.Clear
End With
End Sub
Sub custom_sort_table()
Dim ws As Worksheet
Set ws = ActiveSheet
Dim sortcol As Range
Dim tbl As ListObject
Dim vCustom_Sort As Variant
Set tbl = ws.ListObjects("Table1") 'Set/adjust table name
Set sortcol = Range("Table1[Status]") 'Set/adjust table column you want to sort (i.e. table name + column name)
vCustom_Sort = Array("Published", "Submitted", "Distributed", "Amending", "Awaiting Sign-off", "Materials Drafting", "Working Up", "Arranging Interview", "Sourcing Information/Images", "Confirmed", "Pitched", "On Hold", "Archive")
Application.AddCustomList ListArray:=vCustom_Sort
With ActiveWorkbook.Worksheets("Activity")
With tbl.Sort 'sort table
.SortFields.Clear 'clear previous sorting
.SortFields.Add Key:=sortcol, SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:=Application.CustomListCount
.Header = xlYes 'Ignore heading
.Apply 'Need to apply sorting, otherwise it won't change sort
End With
End With
End Sub
-----------------------
Sub custom_sort()
Dim vCustom_Sort As Variant, rr As Long
vCustom_Sort = Array("Published", "Submitted", "Distributed", "Amending", "Awaiting Sign-off", "Materials Drafting", "Working Up", "Arranging Interview", "Sourcing Information/Images", "Confirmed", "Pitched", "On Hold", "Archive")
Application.AddCustomList ListArray:=vCustom_Sort
With ActiveWorkbook.Worksheets("Activity")
.Sort.SortFields.Clear
rr = .Cells(.Rows.Count, "B").End(xlUp).Row
With .Range("A2:L" & rr)
.Sort Key1:=.Columns(2), Order1:=xlAscending, DataOption1:=xlSortNormal, _
Orientation:=xlTopToBottom, Header:=xlYes, MatchCase:=False, _
OrderCustom:=Application.CustomListCount + 1
End With
.Sort.SortFields.Clear
End With
End Sub
Sub custom_sort_table()
Dim ws As Worksheet
Set ws = ActiveSheet
Dim sortcol As Range
Dim tbl As ListObject
Dim vCustom_Sort As Variant
Set tbl = ws.ListObjects("Table1") 'Set/adjust table name
Set sortcol = Range("Table1[Status]") 'Set/adjust table column you want to sort (i.e. table name + column name)
vCustom_Sort = Array("Published", "Submitted", "Distributed", "Amending", "Awaiting Sign-off", "Materials Drafting", "Working Up", "Arranging Interview", "Sourcing Information/Images", "Confirmed", "Pitched", "On Hold", "Archive")
Application.AddCustomList ListArray:=vCustom_Sort
With ActiveWorkbook.Worksheets("Activity")
With tbl.Sort 'sort table
.SortFields.Clear 'clear previous sorting
.SortFields.Add Key:=sortcol, SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:=Application.CustomListCount
.Header = xlYes 'Ignore heading
.Apply 'Need to apply sorting, otherwise it won't change sort
End With
End With
End Sub
Calculate average of any two numbers in a given array in JavaScript?
const
values = [4, 5, 10, 9, 8];
for (let i = 0, l = values.length - 1; i < l; i++) {
for (j = i + 1; j < values.length; j++) {
const average = (values[i] + values[j]) / 2;
console.log(values[i], values[j], '|', average, '|', ...values.filter(v => v > average));
}
}
-----------------------
function solve(arr) {
arr.sort(function (a, b) { return a - b });
let firstMinimum = arr[0];
let secondMinimun = arr[1];
let avg = (firstMinimum + secondMinimun) / 2;
for (let i = 0; i < arr.length; i++) {
if (arr[i] > avg) console.log(arr[i]);
}
}
solve([4, 5, 10, 9, 8]);
-----------------------
let arr = [4,5,10,9,8]
arr.sort((a,b) => a-b) // sorted array
function greaterThanAverage(x,y){
let average = (x+y)/2
let index = arr.findIndex(e => e > average )
return arr.slice(index == -1 ? arr.length : index)
}
console.log(greaterThanAverage(5,9))
console.log(greaterThanAverage(10,9))
console.log(greaterThanAverage(5,4))
console.log(greaterThanAverage(30,4))
-----------------------
const values = [4, 5, 10, 9, 8];
const minValue = Math.min(...values);
values.splice(values.indexOf(minValue),1);
const secondMinValue = Math.min(...values);
const minAverage = (minValue + secondMinValue)/2;
const result = values.filter(val => val > minAverage);
Why ambiguous reference error while using Left without parameters type?
scala> for (v1 <- Right(2)) yield v1
res13: scala.util.Either[Nothing,Int] = Right(2)
for {
v1 <- Left[Int,Int](1)
v2 <- Right[Int,Int](2)
v3 <- Right[Int,Int](3)
v4 <- Left[Int,Int](4)
} yield v1 + v2 + v3 + v4
-----------------------
scala> for (v1 <- Right(2)) yield v1
res13: scala.util.Either[Nothing,Int] = Right(2)
for {
v1 <- Left[Int,Int](1)
v2 <- Right[Int,Int](2)
v3 <- Right[Int,Int](3)
v4 <- Left[Int,Int](4)
} yield v1 + v2 + v3 + v4
Counting total number of paper pieces
int func(int a, int b, int c, int d, int n) {
if (n == 0) return (a + b + c + d);
if (n % 2 == 0) return func(a + b, a, c + d, c, n - 1);
else return func(a + c, b + d, a, b, n - 1);
}
Permutations of the same 4 digits resulting into 2 pairs
def xnor_pairs(seq):
# Create two pointers: one on the start and another at the end
i0 = 0
i1 = len(seq) - 1
pairs = []
# Repeat this until the start pointer has not reached the end
while i0 < len(seq) - 1:
a, b = seq[i0], seq[i1]
# If the start and end indexes are equal
if i0 == i1:
# Move the start pointer one position closer to the end
i0 += 1
# Move the end pointer back to the end
i1 = len(seq) - 1
continue
# If the condition is satisfied (a XNOR b == -1)
if ~(a ^ b) == -1:
# Append to the pairs
pairs.append((a, b))
# Move the end pointer one position closer to the start
i1 -= 1
return pairs
print(xnor_pairs([1, 2, 3, 3, 4, 4, 4, 10, 10, 10]))
# Output: [(3, 3), (4, 4), (4, 4), (4, 4), (10, 10), (10, 10), (10, 10)]
Async operations when instance created
this.ready = Promise.all([URL1, URL2, URL3].map((url) => { this.myAsyncCall(url); }));
this.ready = Promise.all([URL1, URL2, URL3].map((url) => { return this.myAsyncCall(url); }));
this.ready = Promise.all([URL1, URL2, URL3].map((url) => this.myAsyncCall(url)));
notifyUrls(item, (res) => {
resolve(res);
});
notifyUrls(item, resolve);
const asyncOperation = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 2000);
});
};
const asyncOperation = () => new Promise(resolve => setTimeout(resolve, 2000));
-----------------------
this.ready = Promise.all([URL1, URL2, URL3].map((url) => { this.myAsyncCall(url); }));
this.ready = Promise.all([URL1, URL2, URL3].map((url) => { return this.myAsyncCall(url); }));
this.ready = Promise.all([URL1, URL2, URL3].map((url) => this.myAsyncCall(url)));
notifyUrls(item, (res) => {
resolve(res);
});
notifyUrls(item, resolve);
const asyncOperation = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 2000);
});
};
const asyncOperation = () => new Promise(resolve => setTimeout(resolve, 2000));
-----------------------
this.ready = Promise.all([URL1, URL2, URL3].map((url) => { this.myAsyncCall(url); }));
this.ready = Promise.all([URL1, URL2, URL3].map((url) => { return this.myAsyncCall(url); }));
this.ready = Promise.all([URL1, URL2, URL3].map((url) => this.myAsyncCall(url)));
notifyUrls(item, (res) => {
resolve(res);
});
notifyUrls(item, resolve);
const asyncOperation = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 2000);
});
};
const asyncOperation = () => new Promise(resolve => setTimeout(resolve, 2000));
-----------------------
this.ready = Promise.all([URL1, URL2, URL3].map((url) => { this.myAsyncCall(url); }));
this.ready = Promise.all([URL1, URL2, URL3].map((url) => { return this.myAsyncCall(url); }));
this.ready = Promise.all([URL1, URL2, URL3].map((url) => this.myAsyncCall(url)));
notifyUrls(item, (res) => {
resolve(res);
});
notifyUrls(item, resolve);
const asyncOperation = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 2000);
});
};
const asyncOperation = () => new Promise(resolve => setTimeout(resolve, 2000));
-----------------------
this.ready = Promise.all([URL1, URL2, URL3].map((url) => { this.myAsyncCall(url); }));
this.ready = Promise.all([URL1, URL2, URL3].map((url) => { return this.myAsyncCall(url); }));
this.ready = Promise.all([URL1, URL2, URL3].map((url) => this.myAsyncCall(url)));
notifyUrls(item, (res) => {
resolve(res);
});
notifyUrls(item, resolve);
const asyncOperation = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 2000);
});
};
const asyncOperation = () => new Promise(resolve => setTimeout(resolve, 2000));
-----------------------
this.ready = Promise.all([URL1, URL2, URL3].map((url) => { this.myAsyncCall(url); }));
this.ready = Promise.all([URL1, URL2, URL3].map((url) => { return this.myAsyncCall(url); }));
this.ready = Promise.all([URL1, URL2, URL3].map((url) => this.myAsyncCall(url)));
notifyUrls(item, (res) => {
resolve(res);
});
notifyUrls(item, resolve);
const asyncOperation = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 2000);
});
};
const asyncOperation = () => new Promise(resolve => setTimeout(resolve, 2000));
-----------------------
this.ready = Promise.all([URL1, URL2, URL3].map((url) => { this.myAsyncCall(url); }));
this.ready = Promise.all([URL1, URL2, URL3].map((url) => { return this.myAsyncCall(url); }));
this.ready = Promise.all([URL1, URL2, URL3].map((url) => this.myAsyncCall(url)));
notifyUrls(item, (res) => {
resolve(res);
});
notifyUrls(item, resolve);
const asyncOperation = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 2000);
});
};
const asyncOperation = () => new Promise(resolve => setTimeout(resolve, 2000));
Interview question, setTimeout should be called first before console.log
function callMe(delay) {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Called");
// Resolve Promise, when Timeout is over
resolve();
}, delay);
});
}
// Async Main Function
(async () => {
const delays = [500, 1000, 1500];
for (let delay of delays) {
// Await the Timeout with the Promise
await callMe(delay);
}
console.log("Completed");
})();
Dynamic number of currying strings
const func = (arg) => {
const args = [arg];
const inner = (arg) => {
args.push(arg);
return inner;
};
inner.join = () => args.join(':');
return inner;
};
console.log(func('hello')('world').join(':'));
console.log(func('hello')('world')('today').join(':'));
How type casting works in Python?
def get():
prompt = 'Give a number or a word.\n'
x = input(prompt)
try:
float(x)
print('You entered a number.')
except:
print('You entered a string.')
QUESTION
How it is possible to cast parent to child in c#
Asked 2021-Jun-15 at 12:54A few days ago in an interview, i was asked to explain following cases:
public class Parent
{
}
public class Child:Parent
{
}
Case1:
Parent p = new Child();
var c = (Child)p;
Case2:
Parent p = new Parent();
var c = (Child)p;
I said case1
is valid and case2
is invalid , but he asked:
Why
case2
is invalid while bothp
variable incase1
andcase2
are Type ofParent
class?
In case2 we get runtime exception by following message:
Unable to cast object of type 'Parent' to type 'Child
While in case1
p
variable was also type of Parent
class.
He wanted me to explain it from point of stack
and heap
memory.
Have you any idea?
Update:
The very spot that interviewer misguided me was exactly where he said in both cases p
is type of 'parent' class, based on the answers, just static types of both variables are 'parent', but in run-time they have different types and it's run-time type that really matters.
ANSWER
Answered 2021-Jun-15 at 12:54You must make a distinction between the static type of a variable (the type known at compile time) and the run time type of an object reference assigned to a variable.
The static type of p
is Parent
in both cases because it is declared as Parent p
. No matter what you assign it. You may even assign it null
.
The run time type of the value of p
after the assignment is Child
in the first case and Parent
in the second case. It would be undetermined if p
was null
.
It is okay to assign a Child
to a Parent
, because the Child
class derives from Parent
. A Child
is therefore a Parent
(in OO terms).
However, a Parent
is not a Child
, because it does not derive from it. Therefore, in the second case, you cannot cast p
to Child
. In the first case the cast is valid, because you cast the object to its actual run time type. It tells the compiler, I know that this object assigned to a Parent
variable is a Child
, so, please, treat it as a Child
. This does not involve any conversion; however, a runtime check will be performed, possibly throwing an exception, if the cast was not allowed.
You were asked to explain it from point of view of stack and heap memory. I'm sorry to say, but this has absolutely nothing to do with stack or heap memory. It has to do with inheritance rules and assignment compatibility.
Of course, here we are dealing with reference types (classes). This allows us to derive Child
from Parent
. This would not be possible with value types (structs). The point is reference type versus value type, not heap versus stack, which is an implementation detail. And btw., a value type (struct) field in a class will also be stored on the heap.
See also: The Stack Is An Implementation Detail, Part One and Two (Eric Lippert's blog)
You did not ask for it but casting to a derived type is mostly preceded by a type test, because you usually do not know the run time type in advance. Let us say that the Child
class adds a new method DriveParentsToDespair()
(only children can do this). Then you could use Type testing with pattern matching to test the type and assign it to a new variable at the same time:
if (p is Child child) {
child.DriveParentsToDespair();
}
This avoids an exception in case p
has a run time type of Parent
.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported
Save this library and start creating your kit
Explore Related Topics
Save this library and start creating your kit