C# Practical Scenarios Interview Questions and Solutions

Aired Consulting 9/05/2009 No Comment
C#.NET Interview Questions and Answers,C# Practical Scenarios and Solutions,C# Realtime Interview Questions,C# Questions for MNCs like Cap Gemini,IBM,Accenture

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 you actually do want to compare references, it can be done as follows: if ((object) str1 == (object) str2) { ... } Here's an example showing how string compares work: using System;
public class StringTest
{
public static void Main(string[] args)
{
Object nullObj = null;
Object realObj = new StringTest();
int i = 10;
Console.WriteLine("Null Object is [" + nullObj + "]n" +
"Real Object is [" + realObj + "]n" +
"i is [" + i + "]n");
// Show string equality operators
string str1 = "foo";
string str2 = "bar";
string str3 = "bar";
Console.WriteLine("{0} == {1} ? {2}", str1, str2, str1 == str2 );
Console.WriteLine("{0} == {1} ? {2}", str2, str3, str2 == str3 );
}}
Output: Null Object is []
Real Object is [StringTest]
i is [10]
foo == bar ? False
bar == bar ? True

What does assert() do?
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.

How do I get deterministic finalization in C#?
In a garbage collected environment, it's impossible to get true determinism. However, a design pattern that we recommend is implementing IDisposable on any class that contains a critical resource. Whenever this class is consumed, it may be placed in a using statement, as shown in the following example:
using(FileStream myFile = File.Open(@"c:temptest.txt",
FileMode.Open))
{
int fileOffset = 0;
while(fileOffset <>
{
Console.Write((char)myFile.ReadByte());
fileOffset++;
}}
When myFile leaves the lexical scope of the using, its dispose method will be called.

How can I get around scope problems in a try/catch?
If you try to instantiate the class inside the try, it'll be out of scope when you try to access it from the catch block. A way to get around this is to do the following: Connection conn = null;

try
{
conn = new Connection();
conn.Open();
}
finally
{
if (conn != null) conn.Close();
}

By setting it to null before the try block, you avoid getting the CS0165 error (Use of possibly unassigned local variable 'conn').

Why do I get an error (CS1006) when trying to declare a method without specifying a return type?
If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj)

How do I convert a string to an int in C#?
Here's an example: using System;

class StringToInt
{
public static void Main()
{
String s = "105";
int x = Convert.ToInt32(s);
Console.WriteLine(x);
}}

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 with the static and external modifiers, and has the DllImport attribute, which tells the compiler that the implementation comes from the user32.dll, using the default name of MessageBoxA. For more information, look at the Platform Invoke tutorial in the documentation.

What is the .NET datatype that allows the retrieval of data by a unique key? HashTable.

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.


My switch statement works differently! Why?
C# does not support an explicit fall through for case blocks.
The following code is not legal and will not compile in C#: switch(x)

{
case 0:
// do something
case 1:
// do something in common with 0
default:
// do something in common with
//0, 1 and everything else
break;
}

To achieve the same effect in C#, the code must be modified
as shown below (notice how the control flows are explicit): class Test

{
public static void Main()
{
int x = 3;
switch(x)
{
case 0:
// do something
goto case 1;
case 1:
// do something in common with 0
goto default;
default:
// do something in common with 0, 1, and anything else
break;
}}}

How can I access the registry from C# code?
By using the Registry and RegistryKey classes in Microsoft.Win32, you can easily access the registry. The following is a sample that reads a key and displays its value:

using System;using Microsoft.Win32;
{
public static void Main(String[] args)
{
RegistryKey regKey;
Object value;
regKey = Registry.LocalMachine;
regKey =
regKey.OpenSubKey("HARDWAREDESCRIPTIONSystemCentralProcessor ");
value = regKey.GetValue("VendorIdentifier");
Console.WriteLine("The central processor of this machine is: {0}.", value);
}}


Q: How do I do implement a trace and assert?
A: Use a conditional attribute on the method:

class Debug
{
[conditional("TRACE")]
public void Trace(string s)
{
Console.WriteLine(s);
}
}

class MyClass
{
public static void Main()
{
Debug.Trace("hello");
}
}

In this example the call to Debug.Trace() is only made if the preprocessor symbol TRACE is defined at the call site. You can define preprocessor symbols on the command line using the /D switch. The restriction on conditional methods is that they must have void return type.
Related Posts

No comments:

 

Aired | Copyright © 2009-2014| All Rights Reserved 2014 | Privacy Policy and Disclaimer

Contact Us | About Us