Technical Interviews – .NET Developers

Some of them may sound silly, does not reflect upon your level of intelligence, others may not be relevant to your job, yet some are designed just to filter experienced candidates who can do the job. Just make sure you have the right answer before walking into the room, that how the system works. This said, some of these are actually things you’d need to know ūüôā

1. What gets printed?

string[] SomeListOfNames = {“Doe”, “Doddie”, “Susan”, “Mary”};
var q = from Name in SomeListOfNames
select Name;

SomeListOfNames[0] = “John Doe”;
foreach (string Person in q)
{
Console.WriteLine(Person);
}

ANS: John Doe, Doddie, Susan, Mary

 

2. Lambda and variable scope:
static int TestFunc(ref int i, int j)
{
SomeFunc deg = (int num) =>
{
int k = 50;
if (i > 0) // Annonymous method can access “i” outside its body (But this won’t compile as “int i” passed in as “ref”!
{
while (i > 0)
{
num++;
i–;
}
}
else
{
SomeFunc deg2 = (int num2) =>
{
while (k > 0) // Annonymous method can access “k” outside its body
{
num2 += z;
k–;
}
return num2;
};
num = deg2(num);
}

return num++;
};
j = deg(j);

return j * 10;
}

static void Main(string[] args)
{
int i = -1;
int j = 0;
int k = TestFunc(ref i, j); <– “i” passed in as “ref”. Lambda can’t access it.
}

Annonymous Method – variable scope? Further, no “ref”, or “out”! No unsafe code.
Quote MSDN:
a. An anonymous method cannot access the ref or out parameters of an outer scope.
b. No unsafe code can be accessed within the anonymous-method-block.
c. Anonymous methods are not allowed on the left side of the is operator.

Also, important to remember, compiler generate class to hold the annonymous method.
http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx
http://stackoverflow.com/questions/2890987/scope-of-variables-inside-anonymous-functions-in-c-sharp
http://www.codeproject.com/Articles/155756/Anonymous-Methods-Behind-the-Scenes

 

3. If you instantiate Z, what gets printed?
class X
{
Y a = new Y(); <- #2
public X()
{
Console.Write(“X”); <- #3
}
}

class Y
{
public Y()
{
Console.Write(“Y”);
}
}

class Z : X
{
Y b = new Y(); <- #1
public Z()
{
Console.Write(“Z”); <- #4
}
}

ANS: YYXZ

 

4. private virtual/abstract method?
class X
{
private virtual void Test()
{
return;
}

Y b = new Y();
public X()
{
Console.Write(“X”);
}
}

ANS: Compile error, “virtual or abstract members cannot be private”

 

5. Will this compile? Y overrides a method in X which isn’t marked virtual

class X
{
private void Shout() // marking “private virtual” will give compiler error
{
Console.WriteLine(“X.Shout”);
}
}

class Y
{
public override void Shout() // If base class didn’t have “virtual void Shout” also would give compile error if you “override” here.
{
Console.WriteLine(“Y.Shout”);
}
}

ANS: “no suitable method found to override”

 

6.

Which can access X.num?
class X
{
private int num = 999;

class Nested
{
public int GetNum(X x)
{
return x.num; //OK
}
}
}

class Y : X
{
class Nested
{
public int GetNum(X x)
{
return x.num; // Compile error
}
}
}

Which can access X.num now?
class X
{
protected int num = 999; <– protected, not private as in prev question

class Nested
{
public int GetNum(X x)
{
return x.num; //OK
}
}
}

class Y : X
{
class Nested
{
public int GetNum(X x) <– to compile, change to “GetNum(Y x)
{
return x.num; // Compile error
}
}
}

 

7. What’s the use of “new” keyword? “new” vs “override”?

class Car
{
public virtual void DescribeCar()
{
System.Console.WriteLine(“Four wheels and an engine.”);
}
}

// Define the derived classes
class ConvertibleCar : Car
{
public void DescribeCar() <– For example, code WILL COMPILE SUCCESSFULLY even if you don’t mark method “new”, but you get Warning 3 ‘SimpleConsole.ConvertibleCar.DescribeCar()’ hides inherited member ‘SimpleConsole.Car.DescribeCar()’. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
{
System.Console.WriteLine(“A roof that opens up.”);
}
}

class Minivan : Car
{
public override void DescribeCar()
{
System.Console.WriteLine(“Carries seven people.”);
}
}

Car car1 = new Car();
car1.DescribeCar();

ConvertibleCar car2 = new ConvertibleCar();
car2.DescribeCar(); <– overridden ConvertibleCar.DescribeCar will be called

Minivan car3 = new Minivan();
car3.DescribeCar(); <– overridden Minivan.DescribeCar will be called

Car[] cars = new Car[3];
cars[0] = new Car();
cars[1] = new ConvertibleCar();
cars[2] = new Minivan();
foreach (Car vehicle in cars)
{
vehicle.DescribeCar(); <– No Polymorphism for cars[1] which is a ConvertibleCar.
}

Console.WriteLine(“Hit any key to exit”);
Console.ReadLine();

http://msdn.microsoft.com/en-us/library/ms173153%28v=vs.80%29.aspx

 

8. const vs readonly
ANS: “The only difference is that const variables are defined in compile time, while readonly variables are defined at runtime during object initialization. You can assign readonly variables from within constructors, so based on the constructor call you may assign readonly values differently.”
http://www.codeproject.com/Articles/38695/UnCommon-C-keywords-A-Look#dcr

 

9. Struct vs Class differences
http://www.jaggersoft.com/pubs/StructsVsClasses.htm
Note in particular struct can implement interfaces (http://blogs.msdn.com/b/abhinaba/archive/2005/10/05/477238.aspx), but doesn’t support inheritance.
 

10. Access to “protected internal” members?
* Same Assembly?
* Nested class?
http://www.codeproject.com/Articles/25078/C-Access-Modifiers-Quick-Reference

 

11. What gets printed?
IList<string> SomeList = new List<string>();
SomeList.Add(“AAA”);
SomeList.Add(“BBB”);
SomeList.Add(“CCC”);
SomeList.Add(“DDD”);
SomeList.Add(“EEE”);

string[] Clone = SomeList.ToArray<string>();
Clone[0] = “ZZZ”;

Console.WriteLine(SomeList[0]); // AAA
Console.WriteLine(Clone[0]); // ZZZ

 

12. What gets printed?
Shallow vs Deep Copy? A shallow copy can be made by simply copying the reference.

IList<Person> SomeList = new List<Person>();
SomeList.Add(new Person() { Name = “John” });
SomeList.Add(new Person() { Name = “Peter” });
SomeList.Add(new Person() { Name = “Wayne” });

Person[] Clone = new Person[3];
SomeList.CopyTo(Clone, 0); // With “CopyTo”, you’d always need preallocate destination array
Clone[0].Name = “Mary”;

Console.WriteLine(SomeList[0].Name); // Mary
Console.WriteLine(Clone[0].Name); // Mary

Person[] Clone2 = null;
Clone2 = Clone.Clone() as Person[];
Person First = Clone2[0];
First.Name = “Jane”;

Console.WriteLine(SomeList[0].Name); // Jane
Console.WriteLine(Clone[0].Name); // Jane
Console.WriteLine(Clone2[0].Name); // Jane

Person[] Clone3 = new Person[3];
Clone.CopyTo(Clone3, 0); // With “CopyTo”, you’d always need preallocate destination array
Clone3[0].Name = “Jean”;

Console.WriteLine(SomeList[0].Name); // Jean
Console.WriteLine(Clone[0].Name); // Jean
Console.WriteLine(Clone2[0].Name); // Jean
Console.WriteLine(Clone3[0].Name); // Jean

Person SomePerson = (from p in Clone3
select p).FirstOrDefault<Person>();
SomePerson.Name = “Marco”;
Console.WriteLine(SomeList[0].Name); // Macro
Console.WriteLine(Clone[0].Name); // Macro
Console.WriteLine(Clone2[0].Name); // Macro
Console.WriteLine(Clone3[0].Name); // Macro

ANS: CopyTo or Clone: It’s always a Shallow Copy.

 

13. “partial” classes – real use
http://www.codeproject.com/Articles/313352/4-real-time-use-of-Partial-classes-and-partial-met#Fundamentalsofpartialclasses
Example 1: ASP.NET
AppliedAlgoWeb.aspx + AppliedAlgoWeb.aspx.cs + AppliedAlgoWeb.aspx.designer.cs
Example 2: LINQ to SQL
AppliedAlgoDb.dbml + AppliedAlgoDb.cs + AppliedAlgoDb.designer.cs

 

14. Nullable types – i.e. System.Nullable<T> – is it value type? or reference type?

bool? bTmp = null;
System.Nullable<bool> bTmp2 = null; // alternatively…
bTmp = false;
if (bTmp.HasValue)
{
if (bTmp == true)
{
Console.Write(“Yes!”);
}
else
{
Console.Write(“No!”);
}
}

ANS: It’s a “struct” (i.e. value type or System.ValueType), so not Reference type.

 

15. struct can implement Interface?
struct Person : IPerson
{
public string Name { get; set; }
}

interface IPerson
{
string Name { get; set; }
}
ANS: Yes! http://blogs.msdn.com/b/abhinaba/archive/2005/10/05/477238.aspx

 

16. Event vs Delegates – Why Events when you have delegates?

ANS: Events are like properties, instead of get/set, we have add/remove
http://csharpindepth.com/Articles/Chapter2/Events.aspx

 

17. Events – how to safe guard against null reference when invocation list is null?

ANS:
public delegate void OnRequestReceivedHandler(object sender);
public event OnRequestReceivedHandler ReqeustReceived = delegate { };

http://www.akadia.com/services/dotnet_delegates_and_events.html

 

18. foreach – IEnumerable? Or IEnumerator
ANS: IEnumerable
* IEnumerable is an interface enforcing a rule that we need to implement the GetEnumerator method.
* GetEnumerator method returns an IEnumerator interface.

http://www.codeproject.com/Articles/571139/Foreach-On-IEnumerable

 

19. What are the different ways to parse and manipulate XML?

Example 1: XmlReader http://www.dotnetperls.com/xmlreader
using (FileStream fileSteam = File.OpenRead(fileName))
{
XmlReaderSettings settings;
settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Document;

using(XmlReader reader = XmlReader.Create(fileSteam, settings))
{
while (reader.Read())
{
// reader.Name|Value
}
}
}

Example 2: XmlDocument (Editable, forward/backward anything you like)
XmlDocument vs XPathDocument: http://msdn.microsoft.com/en-us/library/eh3exdc4(v=vs.110).aspx

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains “<Names>…</Names>”

XmlNodeList xnList = xml.SelectNodes(“/Names/Name”); <– SelectNodes takes an XPath
foreach (XmlNode xn in xnList)
{
string firstName = xn[“FirstName”].InnerText;
string lastName = xn[“LastName”].InnerText;
Console.WriteLine(“Name: {0} {1}”, firstName, lastName);
}

Example 3: XPath (Read only, forward/backward anything you like)
XPathDocument xmlDoc = new XPathDocument(Rdr);
XPathNavigator Nav = xmlDoc.CreateNavigator();
XPathNodeIterator Iter = Nav.Select(“/SERIALIZER_ROOT/SERIALIZER_OBJECT”);
while (Iter.MoveNext())
{
// Iter.Current.Value|InnerText|InnerXml
// Iter.Current.GetAttribute($ATTRIBNAME$)
}

Example 4: System.Xml.Linq – http://www.dotnetcurry.com/showarticle.aspx?ID=564
strXml = System.IO.File.ReadAllText(“Sample.xml”);
var Customers = from Customer in System.Xml.Linq.XElement.Parse(strXml).Element(“Customers”).Elements(“Customer”)
where Customer.Element(“FullAddress”).Element(“Country”).Value == “Canada”
select Customer;
foreach (var Customer in Customers)
{
Console.WriteLine(Customer.ToString());
}

Example 5. Parse using DynamicXmlStream, derived from System.Dynamic.DynamicObject – http://www.codeproject.com/Articles/436406/Power-of-Dynamic-Reading-XML-and-CSV-files-made-ea
dynamic customerOrderXmlReader = DynamicXmlStream.Load(new FileStream(“../../Input/CustomerOrder.xml”, FileMode.Open));
Console.WriteLine(“First Customer’s Company Name = ” + customerOrderXmlReader.Root.Customers.Customer[0].CompanyName.Value);

Basically, “DynamicXmlStream” extends “System.Dynamic.DynamicObject”, you’d need override:
bool TryGetMember(GetMemberBinder binder, out object result)
bool TrySetMember(SetMemberBinder binder, object value)
bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
bool TryConvert(ConvertBinder binder, out object result)
bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)

 

20. abstract vs interface – http://www.codeproject.com/Articles/6118/All-about-abstract-classes
abstract method cannot be private/static/virtual
abstract class cannot be sealed
abstract class can contain abstract+non-abstract properties and methods
(Abstract class can have zero abstract methods or properties)
Purpose?
* abstract class is to declare core functionalities to be implemented by derived classes.
* interface is for peripheral.

 

21. Implement multiple interface with name conflict?

ANS:
interface IShow
{
void Show();
}
interface IShow_Case
{
void Show();
}
class B : IShow, IShow_Case
{
public void IShow.Show()
{
Console.WriteLine(“IShow Interface function”);
}
public void IShow_Case.Show()
{
Console.WriteLine(“IShow_Case Interface function”);
}

static void Main(string[] args)
{
IShow I = new B();
I.Show();
IShow_Case I1 = new B();
I1.Show();
Console.ReadKey(true);
}
}

http://www.c-sharpcorner.com/Blogs/12431/inherit-multiple-interfaces-and-they-have-conflicting-method.aspx

 

22. Stack vs Heap
a. Both in RAM
b. Stack much faster
c. Each thread has its own Stack, all threads shared same heap
d. Value types on Stack and Reference types on heap? — This is false!
What about¬†a “struct” instantiated with “new” operator?
* Each local variable (ie one declared in a method) is stored on the stack. That includes reference type variables – the variable itself is on the stack, but remember that the value of a reference type variable is only a reference (or null), not the object itself. Method parameters count as local variables too, but if they are declared with the ref modifier, they don’t get their own slot, but share a slot with the variable used in the calling code. See my article on parameter passing for more details.
* Instance variables for a reference type are always on the heap. That’s where the object itself “lives”.
* Instance variables for a value type are stored in the same context as the variable that declares the value type. The memory slot for the instance effectively contains the slots for each field within the instance. That means (given the previous two points) that a struct variable declared within a method will always be on the stack, whereas a struct variable which is an instance field of a class will be on the heap.
* Every static variable is stored on the heap, regardless of whether it’s declared within a reference type or a value type. There is only one slot in total no matter how many instances are created. (There don’t need to be any instances created for that one slot to exist though.)

http://yoda.arachsys.com/csharp/memory.html
http://www.programmerinterview.com/index.php/data-structures/difference-between-stack-and-heap/
http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx
https://www.simple-talk.com/dotnet/.net-framework/large-object-heap-compaction-should-you-use-it (Large Object Heap and .NET 4.5 enhancements to support admin of LOH)
 

23. GC – Application wide? Or System wide?
ANS: Each application has its own GC processing.

http://stackoverflow.com/questions/6982409/is-the-garbage-collector-in-net-system-wide-or-application-wide
http://stackoverflow.com/questions/11189932/stack-and-heap-allocation

 

24. What’s GC Gen 0/1/2?
ANS: Garbage Collection – Generation 0 (Newest), 1 (Survive one GC pass), 2 (Survive two GC pass)…
http://csharp.2000things.com/tag/garbage-collection

 

25. Thread Safe Collection classes?
ANS: System.Collections.Concurrent
1. ConcurrentDictionary<TKey, TValue>
2. ConcurrentStack<T>
3. ConcurrentQueue<T>
4. ConcurrentBag<T>
5. BlockingCollection<T>
http://msdn.microsoft.com/en-us/library/dd997369(v=vs.110).aspx
http://www.dotnetperls.com/concurrentdictionary

 

26. IDisposable?
ANS:
* IDisposable can be invoked “Deterministically”, and Garbage Collection invoke Destructor/Finalizer at in-deterministic time.
* “using” statement
http://www.codeproject.com/Articles/319826/IDisposable-Finalizer-and-SuppressFinalize-in-Csha
http://msdn.microsoft.com/en-us/library/ms244737.aspx

Dispose resources “Deterministically”:
a. Managed resources
b. unmanaged resources
By resources, we don’t just mean “Memory” – which too is important for example large Bitmap in memory. But “Resources” could be file handle, database connection… etc

* Note that Destructor/Finalizer not called if Dispose on the instance hasn’t been invoked
http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx

 

27. System.Windows.Forms.Timer vs System.Timers.Timer vs System.Threading.Timer?

ANS:

http://msdn.microsoft.com/en-us/magazine/cc164015.aspx
http://stackoverflow.com/questions/1435876/do-c-sharp-timers-elapse-on-a-separate-thread

 

28. When you abort a thread from Main, you get ThreadAbortException on Main? Or in Thread?
ANS: Thread’s catch statement, not Main where the thread was created/started

 

29. Why not Thread.Abort? “finally” block executed to release unmanaged resources?

ANS: “finally” block always executed on aborts, but
(a) You are not sure if any resources allocated BEFORE “try” block!
(b) Thread aborted when “finally” block executed half way?

Imagine your code open an Excel file, execute some VBA embedded on a thread. Then half way thru thread is aborted?

 

30. Examples of real world usage of annonymous types?

http://stackoverflow.com/questions/11795046/real-world-example-for-anonymous-types-of-c-sharp-net

ANS:
LINQ queries use them a lot:
var productQuery =
from prod in products
select new { prod.Color, prod.Price };
The { prod.Color, prod.Price } is an anonymous type that has a read-only Color and Price property. If you would iterate through the results of that query you could use that type as any other class:

foreach (var v in productQuery)
{
Console.WriteLine(“Color={0}, Price={1}”, v.Color, v.Price);
}
In other words, you didn’t have to define a new class that would look something like this:
public class ColoredPricedItem
{
public Color {get;}
public Price {get;}
}

 

31. Sealed vs private
private class A{}

private class B : A{}

sealed class C{}

// Error 1 ‘SimpleConsole.Test.D’: cannot derive from sealed type ‘SimpleConsole.Test.C’
class D : C{}

 

32. Memory limit?
Addressable Memory? 32bit vs 64bit? 32bit 2GB default, 64 bit 8TB. But you won’t have 8TB Physical Memory –> Paging
Single Object Limit? For both x86/x64, single object < 2GB
http://stackoverflow.com/questions/6107322/memory-limitations-in-a-64-bit-net-application
http://stackoverflow.com/questions/17808946/out-of-memory-exception-on-64bit
http://stackoverflow.com/questions/2399162/process-memory-limit-of-64-bit-process

 

33. Large Object Heap? No compacting – thus performance improvement
http://blogs.msdn.com/b/mariohewardt/archive/2013/06/26/no-more-memory-fragmentation-on-the-large-object-heap.aspx
http://stackoverflow.com/questions/8951836/why-large-object-heap-and-why-do-we-care

 

34. Dynamics vs Var
http://www.codeproject.com/Tips/460614/Difference-between-var-and-dynamic-in-Csharp
http://www.codeguru.com/csharp/article.php/c19053/Using-DynamicObject-and-ExpandoObject.htm

What’s the use of “dynamics”?
Example 1. Extending from “System.Dynamic.DynamicObject” in combination with “System.Xml.Linq.XElement”:
http://www.codeproject.com/Articles/436406/Power-of-Dynamic-Reading-XML-and-CSV-files-made-ea

dynamic customerOrderXmlReader = DynamicXmlStream.Load(new FileStream(“../../Input/CustomerOrder.xml”, FileMode.Open));
foreach (dynamic order in
(customerOrderXmlReader.Root.Orders.Order as DynamicXmlStream).AsDynamicEnumerable().Where(ord => ord.ShipInfo.ShipRegion.Value == “CA”))
{
Console.WriteLine(order.ToString());
Console.WriteLine(new string(‘-‘, 40));
}

Example 2. Invoke method via reflection vs
Reflection
object calc = GetCalculator();
Type calcType = calc.GetType();
object res = calcType.InvokeMember(
“Add”, BindingFlags.InvokeMethod,
null, new object[] { 10, 20 });
int sum = Convert.ToInt32(res);
Dynamics
dynamic calc = GetCalculator();
int sum = calc.Add(10, 20);

35. class vs struct?
ANS:
class: lock, as-operator, inheritance, null, destructor, field initialize
struct: sizeof, stackalloc, default constructor
differences: Equals, stack vs heap

http://www.jaggersoft.com/pubs/StructsVsClasses.htm

 

36. struct on heap or stack?
struct A {}
A a = new A(); –> On heap? Or stack?

ANS: stack

A lot of confusion has been wrought by people explaining the difference between value types and reference types as “value types go on the stack, reference types go on the heap”. This is simply untrue (as stated) and this article attempts to clarify matters somewhat.
http://yoda.arachsys.com/csharp/memory.html
http://www.codeproject.com/Articles/20620/Structs-in-C-Structs-vs-Classes-Heap-or-Stack-Stru

 

37. Stack vs Heap
* The stack is the memory set aside as scratch space for a thread of execution. When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data. When that function returns, the block becomes unused and can be used the next time a function is called. The stack is always reserved in a LIFO order; the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer.
* The heap is memory set aside for dynamic allocation. Unlike the stack, there’s no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time; there are many custom heap allocators available to tune heap performance for different usage patterns.
http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap

 

38. yield return
http://www.dotnetperls.com/yield

foreach (int value in ComputePower(2, 30))
{
Console.Write(value);
Console.Write(” “);
}

public static IEnumerable<int> ComputePower(int number, int exponent)
{
int exponentNum = 0;
int numberResult = 1;
//
// Continue loop until the exponent count is reached.
//
while (exponentNum < exponent)
{
//
// Multiply the result.
//
numberResult *= number;
exponentNum++;
//
// Return the result with yield.
//
yield return numberResult;
}
}

 

39. Predicate<T> vs FUNC<T,TRESULT>?
Predicate<T> is equivalent to FUNC<T,bool>

 

40. What code do you write to constrain a generic dictionary named MyDictionary to have value-type keys with reference type values?
public class MyDictionary<Tkey,TValue>:Dictionary<Tkey,TValue>
where Tkey:struct
where TValue:class
{

}
http://stackoverflow.com/questions/12773990/generic-dictionary-with-value-type-keys-and-reference-type-values

 

41. Initialize a list of string? Syntax?
IList<string> types = new List<string> { “a”, “b”, “c” };

 

42. What gets printed?
class Member
{
public int FreeTickets { get; set; }
}

class Associate : Member
{
public new int FreeTickets { get; set; } <– Note, “new” keyword hides the base class property
}

Associate a = new Associate();
Member b = a;
a.FreeTickets = 1;
b.FreeTickets = 2;
Console.WriteLine(a.FreeTickets); // 1
Console.WriteLine(b.FreeTickets); // 2

 

43. System.Windows.Forms.Timer vs System.Timers.Timer vs System.Threading.Timer
ANS:
System.Windows.Forms: UI thread
System.Timers: UI or worker
System.Threading: thread Worker thread

http://msdn.microsoft.com/en-us/magazine/cc164015.aspx

 

44. Given:
static void SomeOtherFunc(decimal a, decimal b)
{
double c = (double) a / (double) b;
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);

return;
}

Which compiles? select multiples
(a) SomeOtherFunc(3.2m, 2.0);
(b) SomeOtherFunc(3.2m, 2); <– ok
(c) SomeOtherFunc(3.2m, 2m); <– ok
(d) SomeOtherFunc(3.2m, 2d);

http://www.dotnetperls.com/suffix

Continuing from (1), print statements gives if you call SomeOtherFunc(3.00m, 2)?
(a) 3000000, 2, 1.5
(b) 3.00, 2, 1.5 <– Correct
(c) 3, 2, 1.5
(d) 3, 2, 1.75 <– Note this is designed to filter those who’s genuinely retarded

Continuing from (2), print statements if SomeOtherFunc(3.00m, (decimal) 2.00)?
(a) 3000000, 2, 1.5
(b) 3.00, 2, 1.5 <– Correct
(c) 3, 2, 1.5
(d) 3, 2, 1.75

 

45. What’s HashCode?¬†Hashcode vs Equals?

“A hash function is any algorithm that maps data of arbitrary length to data of a fixed length. The values returned by a hash function are called hash values, hash codes, hash sums, checksums or simply hashes. “

It’s perfectly possible for two different object meant to be unequal to have same HashCode!
But Equal should be overridden such that “Equal” object should have same HashCode.
http://en.wikipedia.org/wiki/Hash_function

If ObjA.HashCode==ObjB.HashCode Then ObjA May/MayNot Equals(ObjB)
i.e. Objects with the same hash code must be equal ‚Äď WRONG!

If ObjA.NotEquals(ObjB), Then ObjA.HashCode May/MayNot != ObjA.HashCode
i.e. Unequal objects must have different hash codes ‚Äď WRONG!

int x = 13;
int HashCode = x.GetHashCode();
Object o = new Object();
HashCode = o.GetHashCode();

 

46. What happen Dictionary HashCode collision? Affects only performance. If Equals correct, you’d still retrieve the correct object, just slower.
“Whenever two different object instances yield the same hash code, they are stored in the same internal bucket of the dictionary”

http://stackoverflow.com/questions/2240231/how-well-does-net-dictionary-resolve-collisions

int x = 13;
int y = 13;
HashSet<int> Map = new HashSet<int>();
Map.Add(x);
Map.Add(y); <– OK

Dictionary<int, string> Dict = new Dictionary<int, string>();
Dict.Add(x, “x”);
Dict.Add(y, “y”); <– Exception! You can have two keys with same Hashcode, but not duplicate keys!

Here’s another example,

class Entry
{
    public int Key { get; set; }
    public string Content { get; set; }

    public override int GetHashCode()
    {
        return 1; < Hardcoded to 1 so we have hash collision
    }
}

Entry Entry1 = new Entry() { Key = 1, Content = “xxx” };
Entry Entry2 = new Entry() { Key = 2, Content = “yyy” };
IDictionary<Entry, string> Entries = new Dictionary<Entry, string>();
Entries.Add(Entry1, “aaa”);
Entries.Add(Entry2, “bbb”); < This is OK, won’t throw any exception!
Console.WriteLine(“Entries count: ” + Entries.Count);

 

http://eclipsesource.com/blogs/2012/09/04/the-3-things-you-should-know-about-hashcode/

47. What happen if you forget implement GetHashCode?

Then Base class Object.GetHashCode()
“The GetHashCode method can be overridden by a derived type. If GetHashCode is not overridden, hash codes for reference types are computed by calling the Object.GetHashCode method of the base class, which computes a hash code based on an object’s reference”
http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx

 

48. C# has pointers?

http://www.c-sharpcorner.com/UploadFile/rajeshvs/PointersInCSharp11112005051624AM/PointersInCSharp.aspx

int x = 100;
int *ptr = & x;

 

49. unsafe/fixed –¬†What are they and when do we need them?
http://www.dotnetperls.com/fixed
http://www.dotnetperls.com/unsafe

unsafe // Also need Project build configuration to “Allow unsafe code”
{
int num = 12345;
int* ptr = &num;
Console.WriteLine(*ptr);
Console.WriteLine(ptr->ToString());
}

unsafe
{
string value = “ABCDE”;

/*
Objects in memory are moved at almost any time. This makes garbage collection possible. But when we use unsafe pointers to         memory addresses, that memory must not be moved. The fixed statement fixes memory in one location.
*/
fixed (char* pointer = value)
{
// Add one to each of the characters.
for (int i = 0; pointer[i] != ”; ++i)
{
Console.Write(pointer[i]);
pointer[i]++;
}
}
}

So, why pin/fix memory? For example copy a string into a byte[] – following method eliminate Intermediate variable of type byte[], and the resultant Garbage Collection – thus improvement in Performance (Fewer garbage collection).

http://stackoverflow.com/questions/21981132/whats-the-use-of-c-sharp-keyword-fixed-unsafe/21981333?noredirect=1#comment33311290_21981333
http://stackoverflow.com/questions/15307431/c-sharp-copy-variables-into-buffer-without-creating-garbage

FROM:
int variableToCopy = 9861;
byte[] buffer = new byte[1024];
byte[] bytes = BitConverter.GetBytes(variableToCopy); <– Conversion not necessary
Buffer.BlockCopy(bytes, 0, buffer, 0, 4); <– Replaced by directly referencing memory location: *(int*)pbuffer = v1;
float anotherVariableToCopy = 6743897.6377f;
bytes = BitConverter.GetBytes(anotherVariableToCopy);
Buffer.BlockCopy(bytes, 0, buffer, 4, sizeof(float));

TO – basically, you skipped call to Buffer.BlockCopy and Buffer.BlockCopy:
int v1 = 123;
float v2 = 253F;
byte[] buffer = new byte[1024];
fixed (byte* pbuffer = buffer)
{
//v1 is stored on the first 4 bytes of the buffer:
*(int*)pbuffer = v1;
pbuffer += 4; //4 bytes per int

//v2 is stored on the second 4 bytes of the buffer:
*(float*)pbuffer = v2;
}

50. Jagged array? What’s it?
ANS: http://www.dotnetperls.com/jagged-array

 

51. What are the different ways to parse and compose XML?

ANS

a. XmlReader – fast forward only, read only

b. XmlDocument – forward/backward, read+write

c. XPathDocument – forward/backward, read only

d. System.Xml.Linq – forward/backward, more terse syntax than (a)-(c)

e. DynamicXmlStream – most terse syntax among all, read only

XML/xpath/XSL
http://w3schools.com
http://www.indiabix.com/technical/dotnet/xml/

Example 1: XmlReader http://www.dotnetperls.com/xmlreader
using (FileStream fileSteam = File.OpenRead(fileName))
{
XmlReaderSettings settings;
settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Document;

using(XmlReader reader = XmlReader.Create(fileSteam, settings))
{
while (reader.Read())
{
// reader.Name|Value
}
}
}

Example 2: XmlDocument (Editable, forward/backward anything you like)
XmlDocument vs XPathDocument: http://msdn.microsoft.com/en-us/library/eh3exdc4(v=vs.110).aspx

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains “<Names>…</Names>”

XmlNodeList xnList = xml.SelectNodes(“/Names/Name”); <– SelectNodes takes an XPath
foreach (XmlNode xn in xnList)
{
string firstName = xn[“FirstName”].InnerText;
string lastName = xn[“LastName”].InnerText;
Console.WriteLine(“Name: {0} {1}”, firstName, lastName);
}

Example 3: XPath (Read only, forward/backward anything you like)
XPathDocument xmlDoc = new XPathDocument(Rdr);
XPathNavigator Nav = xmlDoc.CreateNavigator();
XPathNodeIterator Iter = Nav.Select(“/SERIALIZER_ROOT/SERIALIZER_OBJECT”);
while (Iter.MoveNext())
{
// Iter.Current.Value|InnerText|InnerXml
// Iter.Current.GetAttribute($ATTRIBNAME$)
}

Example 4: System.Xml.Linq – http://www.dotnetcurry.com/showarticle.aspx?ID=564
strXml = System.IO.File.ReadAllText(“Sample.xml”);
var Customers = from Customer in System.Xml.Linq.XElement.Parse(strXml).Element(“Customers”).Elements(“Customer”)
where Customer.Element(“FullAddress”).Element(“Country”).Value == “Canada” || Customer.Attribute(“Country”).Value == “CA”
select Customer;
foreach (var Customer in Customers)
{
Console.WriteLine(Customer.ToString());
}

Example 5. Parse using DynamicXmlStream, derived from System.Dynamic.DynamicObject – http://www.codeproject.com/Articles/436406/Power-of-Dynamic-Reading-XML-and-CSV-files-made-ea
dynamic customerOrderXmlReader = DynamicXmlStream.Load(new FileStream(“../../Input/CustomerOrder.xml”, FileMode.Open));
Console.WriteLine(“First Customer’s Company Name = ” + customerOrderXmlReader.Root.Customers.Customer[0].CompanyName.Value);

Basically, “DynamicXmlStream” extends “System.Dynamic.DynamicObject”, you’d need override:
bool TryGetMember(GetMemberBinder binder, out object result)
bool TrySetMember(SetMemberBinder binder, object value)
bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
bool TryConvert(ConvertBinder binder, out object result)
bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)

 

52.¬†What’s¬†System.Collections.ObjectModel.ObservableCollection and INotifyPropertyChanged? When do we need them?

ANS
For example, if your WPF form binding to an observable collection, add/remove elements will cause WPF to rebind the list.
ObservableCollection<ConnectionConfiguration> ConnectionList

However, change to element within the collection will not propagate to user interface automatically, unless you implement INotifyPropertyChanged.

public class ConnectionConfiguration : System.ComponentModel.INotifyPropertyChanged, ICloneable
{
public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(String Info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(Info));
}
}

public string ConnectionName
{
get { return _ConnectionName; }
set {
_ConnectionName = value;
NotifyPropertyChanged(“ConnectionName”);
}
}

}

REF:

http://stackoverflow.com/questions/1427471/observablecollection-not-noticing-when-item-in-it-changes-even-with-inotifyprop/14919127#14919127
http://www.codeproject.com/KB/WPF/BeginWPF5.aspx
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

 

53. Is DTC (Distributed Transaction Coordinator) a requirement for TransactionScope to work?
“TransactionScope uses the LTM – Lightweight Transaction Manager in .Net. Only if you open connections against more than one database should TransactionScope promote the transaction to the 2PC-based TX-manager, DTC.”
http://stackoverflow.com/questions/11243855/transactionscope-alternative-without-dtc

 

54.¬†Race condition (volatile) vs Deadlocks –
“The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.
The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access.”

http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/
http://msdn.microsoft.com/en-us/library/x13ttww7.aspx

 

55. How do different threads talks to each other and to main thread?

a. Among workers threads?

* Context object? AppDomain.CurrentDomain.Get/SetData

* Shared thread start arguments

b. Between UI thread and workers thread?

* System.ComponentModel.BackgroundWorker Class

* WPF dispatcher object?

Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{

}
));

 

56. TCP vs UDP?

ANS:

TCP Connection Oriented, from one IP to another IP. Examples, HTTP, HTTPs, FTP, SMTP, Telnet

UDP connection-less, stateless. Examples, DNS, DHCP, TFTP, SNMP, RIP, VOIP.

REF:

http://www.diffen.com/difference/TCP_vs_UDP

TcpListener-TcpClient/UdpListener-UdpClient
http://www.jarloo.com/c-udp-multicasting-tutorial/

 

57.  Annonymous Types and Edge Cases РWhich line will cause compile error? ANS: Highlighted red

var point = new { X = 13, Y = 7 };
var point2 = new { X = 3, Y = 4 };
var point3 = new { X = 3.1, Y = 4 };
var point4 = new { Y = 4, X = 3 };
// var point5 = new { X = null }; // compile error, initializer cannot be null

// point = 1; // Compile error, point already been assigned to an annonymous type. You can’t assign to it anything of different type.
point = point2; // This is fine
// point = point3; // point3 is off different annonymous type as X = double, thus again compile error
// point = point4; // point4 also considered a different annonymous type as X/Y order swapped, thus compile error

dynamic x = 2.3;
x = “Some other shit”;

REF: http://geekswithblogs.net/BlackRabbitCoder/archive/2012/06/21/c.net-little-wonders-the-joy-of-anonymous-types.aspx

 

58. Named methods, Anonymous Delegate/Method vs Lambda expression?

ANS:

Old days: Named Delegate
public delegate int FoldIntDelegate(int a, int b);

public int Fold(FoldIntDelegate fid, params int[] list)
{
int result = 1;
foreach (int i in list)
result = fid(result, i);
return result;
}

int val = Fold(new FoldIntDelegate(delegate(int a, int b) { return a * b; }), 1, 3, 5, 7, 9);

.NET 2 Anonymous Delegate
int val = Fold(delegate(int a, int b) { return a * b; }, 1, 3, 5, 7, 9);

.NET 3 Lambda expression
int val = Fold((a, b) => a * b, 1, 3, 5, 7, 9);

REF

http://www.switchonthecode.com/tutorials/csharp-tutorial-the-lambda-operator

http://en.csharp-online.net/CSharp_Enhancements_for_LINQ%E2%80%94Use_Lambda_Expressions

 

59. Memory limit? Addressable Memory? 32bit vs 64bit?

ANS:

a. Addressable Memory: 32bit 2GB default, 64 bit 8TB.

b. Physical Memory: You won’t have 8TB Physical Memory. As soon as your application consumes more than available physical memory,¬†Paging occurs and system slow significantly. Check with permon, “Avg Disk Queue length”, it should be a number smaller than 2.

c. Single Object Limit? For both x86/x64, single object < 2GB
http://stackoverflow.com/questions/6107322/memory-limitations-in-a-64-bit-net-application
http://stackoverflow.com/questions/17808946/out-of-memory-exception-on-64bit
http://stackoverflow.com/questions/2399162/process-memory-limit-of-64-bit-process

Large Object Heap? No compacting
http://blogs.msdn.com/b/mariohewardt/archive/2013/06/26/no-more-memory-fragmentation-on-the-large-object-heap.aspx
http://stackoverflow.com/questions/8951836/why-large-object-heap-and-why-do-we-care

 

60. Stack size has limit?

ANS:

Yes if exceeded, you get a StackOverflowException.  The default stack size for a .NET application is 1 MB (default is 256 KB for 32-bit ASP.NET apps and 512 KB for 64-bit ASP.NET apps)
http://stackoverflow.com/questions/823724/stack-capacity-in-c-sharp
http://www.atalasoft.com/cs/blogs/rickm/archive/2008/04/22/increasing-the-size-of-your-stack-net-memory-management-part-3.aspx

 

61. Dynamics vs Var?

ANS:
“var”: “Implicity type”. “var” is resolved at the compile time, and has Intellisense support.
“dynamic”: When you define a variable of type dynamic, compiler internally performs two steps. The first thing compiler does is, it converts the type to System.Object and then it postpones all the type validation to the runtime. Also, “dynamic” has Intellisense support.
http://www.codeproject.com/Articles/661824/Dynamic-vs-Var-vs-Object

 

62. Polymorphism – What’s “vtable” and how’s it work?

ANS: All instances of that class shares one vtable
http://www.programmerinterview.com/index.php/c-cplusplus/how-vtables-work/

 

63. What’s Reflection and how does it work?

ANS: Quote article by ¬†hosted on¬†Codeproject, ¬†“Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and type information at runtime. The classes that give access to the metadata of a running program are inSystem.Reflection.¬†System.Reflection¬†namespace defines the following types to analyze the module’s metadata of an assembly:Assembly,¬†Module,¬†Enum,¬†ParameterInfo,¬†MemberInfo,¬†Type,¬†MethodInfo,¬†ConstructorInfo,¬†FieldInfo,EventInfo, and¬†PropertyInfo. Whenever a .NET project is built, the code will be get complied into Intermediate language and then packaged in assembly. An assembly contains metadata which has the information about the type of classes defined meaning it contains all the required information about the members, fields, constructors, properties, methods, function, etc. used in the class for building the package.”

http://www.codeproject.com/Tips/791017/Reflection-Concept-and-Late-Binding-in-Csharp

 

64. How do you monitor  a process thread counts and memory consumption?

ANS:

Memory
Process currentProcess =System.Diagnostics.Process.GetCurrentProcess();long totalBytesOfMemoryUsed = currentProcess.WorkingSet64;

(This, however, doesn’t give you allocation in Gen 0/1/2 and LOH)

Thread Count
Process[] proc = Process.GetProcessesByName(“youprocess”);
Console.WriteLine(proc[0].Threads.Count.ToString());

http://stackoverflow.com/questions/1345797/how-to-get-how-many-threads-are-running-in-multithreaded-windows-service-applica
http://stackoverflow.com/questions/2342023/how-to-measure-the-total-memory-consumption-of-the-current-process-programatical
http://stackoverflow.com/questions/9349219/how-to-get-the-heap-memory-allocated-to-each-generation-gen0-gen1-gen2

 

65. Optimistic vs Pessemistic locking?

ANS: http://stackoverflow.com/questions/129329/optimistic-vs-pessimistic-locking

 

Not having enough of this? Here’s another list which I find useful:¬†http://www.hanselman.com/blog/WhatGreatNETDevelopersOughtToKnowMoreNETInterviewQuestions.aspx

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s