RSS Feed for C# Interview QuestionsCategory: C# Interview Questions

Why does DllImport not work for me? »

All methods marked with the DllImport attribute must be marked as public static extern.

Are private class-level variables inherited? »

Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited.

How do I simulate optional parameters to COM calls? »

You must use the Missing class and pass Missing.Value (in System.Reflection) for any values that have optional parameters.

How do you directly call a native function exported from a DLL? »

Here’s a quick example of the DllImport attribute in action:
using System.Runtime.InteropServices; \
class C
{
[DllImport(\"user32.dll\")]
public static extern int MessageBoxA(int h, string m, string c, int type);
public static int Main()
{
return MessageBoxA(0, \”Hello World!\”, \”Caption\”, 0);
}
}
This example shows the minimum requirements for declaring a C# method that is implemented in a native DLL. The method C.MessageBoxA() is declared [...]

How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#? »

You want the lock statement, which is the same as Monitor Enter/Exit:
lock(obj) { // code }
translates to
try {
CriticalSection.Enter(obj);
// code
}
finally
{
CriticalSection.Exit(obj);
}

How do you mark a method obsolete? »

[Obsolete] public int Foo() {…}
or
[Obsolete(\"This is a message describing why this method is obsolete\")] public int Foo() {…}
Note: The O in Obsolete is always capitalized.

How do you specify a custom attribute for the entire assembly (rather than for a class)? »

Global attributes must appear after any top-level using clauses and before the first type or namespace declarations. An example of this is as follows:
using System;
[assembly : MyAttributeClass] class X {}
Note that in an IDE-created project, by convention, these attributes are placed in AssemblyInfo.cs.

How does one compare strings in C#? »

In the past, you had to call .ToString() on the strings when using the == or != operators to compare the strings’ values. That will still work, but the C# compiler now automatically compares the values instead of the references when the == or != operators are used on string types. If [...]