C# Program Examples, Interview Questions and Answers

C# Program Examples, Practical Scenarios, Program Code Questions, Interview Questions and Answers.

Q: How do I create a multi-language multi-file assembly?A: Unfortunately, this is currently not supported in the IDE. In order to do this from the command line, you must compile your projects into netmodules (/target:module on the C# compiler), then use the command line tool al.exe (alink) to link these netmodules together.

Q: How do I simulate optional parameters to COM calls?A: You must use the Missing class, and pass Missing.Value (in System.Reflection) for any values that have optional parameters.

Q: Is there an equivalent to C++'s default values for function arguments?A: Default arguments are not supported but you can attain the same effect through function overloading.

The reason we prefer overloading as the solution to this problem is that it allows you, at a later time, to change the default value of a parameter without having to recompile existing client code. With C++ style default values, the defaults get burned into the client code, and you can therefore never change them once you've published an API.

Q: Is there a way of specifying which block or loop to break out of when working with nested loops?A: The easiest way is to use goto:
using System;
class BreakExample

{public static void Main(String[] args){for(int i=0; i<3 data-blogger-escaped-j="=">

Q: How do I get deterministic finalization in C#?
A:
In a garbage collected environment its 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 for example: using(FileStream myFile = File.Open(@"c:\temp\test.txt", FileMode.Open))
{
int fileOffset = 0; while(fileOffset <>Q: Does C# support variable arguments (vararg's) on methods?

A: The params keyword lets you specify a method parameter that takes an argument where the number of arguments is variable. No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration. Here's an example:

using System; public class MyClass { public static void UseParams(params int[] list) { for ( int i = 0 ; i < i =" 0" myarray =" new" s = "105" x =" Convert.ToInt32(s);">Q: How do you specify a custom attribute for the entire assembly (rather than for a class)?
A: Global attributes must appear after any top-level using clauses and before the first type or namespace declarations. Example Usage: using System; [assembly : MyAttributeClass] class X {} Note that in IDE created project, by convention, these attributes are placed in AssemblyInfo.cs.

Q: How do I register my code for use by classic COM clients?
A: Use the regasm.exe utility to generate a type library (if needed) and the necessary entries in the Windows Registry to make a class available to classic COM clients. Once a class is registered in the Windows Registry with regasm.exe, a COM client can use the class as though it were a COM class.

Q: When using multiple compilation units (C# source files), how is the executable's name determined?
A: The executable's name is the same as the source file's name that has the Main() method. You can also specify the executable's name by using the /out argument from the command line when compiling. For example: C:\>csc /out:myname.exe file1.cs file2.cs will name your executable 'myname.exe'.

Q: How does one compare strings in C#?A: 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

Q: Can I define a type that is an alias of another type (like typedef in C++)?A: Not exactly. You can create an alias within a single file with the "using" directive:
using System;
using Integer = System.Int32; // alias
But you can't create a true alias, one that extends beyond the file it is declared in. Refer to the C# spec for more info on the 'using' statement's scope.

Q: What is the difference between a struct and a class in C#?A: From language spec:
The list of similarities between classes and structs is longstructs can implement interfaces, and can have the same kinds of members as classes. Structs differ from classes in several important ways, however: structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiatedone for the array and one each for the 100 elements.

Q: How can I get the ASCII code for a character in C#?A: Casting the char to an int will give you the ASCII value:
char c = 'f';
System.Console.WriteLine((int)c);
or for a character in a string:
System.Console.WriteLine((int)s[3]);
The base class libraries also offer ways to do this with the Convert class or Encoding classes if you need a particular encoding.

Q: From a versioning perspective, what are the drawbacks of extending an interface as opposed to extending a class?A: With regards to versioning, interfaces are less flexible than classes.

With a class, you can ship version 1 and then in version 2 decide to add another method. As long as the method is not abstract (i.e. as long as you provide a default implementation of the method), any existing derived classes continue to function with no changes.

Because interfaces do not support implementation inheritance, this same pattern does not hold for interfaces. Adding a method to an interface is like adding an abstract method to a base class--any class that implements the interface will break because the class doesn't implement the new interface method.

Q: Is it possible to inline assembly or IL in C# code?A: No.

Q: Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace?A: There is no way to restrict to a namespace. Namespaces are never units of protection. But if you're using assemblies, you can use the 'internal' access modifier to restrict access to only within the assembly.

Q: If I return out of a try/finally in C#, does the code in the finally-clause run?A: Yes. The code in the finally always runs. Whether you return out of the try block or even if you do a "goto" out of the try, the finally block always runs. For example:
using System;
class main
{
public static void Main()
{
try
{
Console.WriteLine("In Try block");
return;
}
finally
{
Console.WriteLine("In Finally block");
}
}
}


Both "In Try block" and "In Finally block" will be displayed. Performance-wise, having the return in the try block or after the try-finally block, it is not affected either way. The compiler treats it as if the return was outside the try block anyway. If it's a return without an expression (as it is above), the IL emitted is identical whether the return is inside or outside of the try. If the return has an expression, there's an extra store/load of the value of the expression (since it has to be computed within the try block).

Q: Does C# support try-catch-finally blocks?A: Yes. Try-catch-finally blocks are supported by the C# compiler. Here's an example of a try-catch-finally block:
using System;
public class TryTest
{
static void Main()
{
try
{
Console.WriteLine("In Try block");
throw new ArgumentException();
}
catch(ArgumentException n1)
{
Console.WriteLine("Catch Block");
}
finally
{
Console.WriteLine("Finally Block");
}
}
}

Output:
In Try Block
Catch Block
Finally Block

Q: Is it possible to have a static indexer in C#?A: No. Static indexers are not allowed in C#.
Related Posts

No comments:

 

Aired | Copyright © 2009-2014| All Rights Reserved 2014

Contact Us | About Us