Monday 15 June 2015

C# Interview Questions

difference between Convert.toString and .toString in .Net

int i = 0; 
MessageBox.Show(i.ToString()); 
MessageBox.Show(Convert.ToString(i));
We can convert the integer “i” using “i.ToString()” or “Convert.ToString” so what is the difference. The basic difference between them is “Convert” function handles NULLS while “i.ToString()” does not it will throw a NULL reference exception error. So as a good coding practice using “convert” is always safe.
string str = NULL; 
MessageBox.Show(str.ToString());  //throw an Error
MessageBox.Show(Convert.ToString(str));


What is value type and reference type with example
Read: Here
what is anonymous types
Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.
You create anonymous types by using the new operator together with an object initializer. 
Read: Here Here

what is extension method

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type 

Write a program to print reverse of a given number?

public int reverseNumber(int Number)
{
int ReverseNumber = 0;
while(Number > 0)
{
ReverseNumber = (ReverseNumber * 10) + (Number % 10);
Number = Number / 10;
}
return ReverseNumber;
}

how to reverse a string in c#

1. Manual Reversal 
string input = "hello String";
string output = "";
for (int i = input.Length - 1; i >= 0; i--)
{
    output += input[i];
}
a new temporary string is created each time you add a single character to the output string.
2. Array.Reverse()
string input = "hello world";
char[] inputarray = input.ToCharArray();
Array.Reverse(inputarray);
string output = new string(inputarray);
First we convert the string to a character array, then we revert the array, and finally we construct a new string from the array. 
3. LINQ
string input = "hello world";
string output = new string(input.ToCharArray().Reverse().ToArray());

 The string is again converted to a char array. Array implements IEnumerable, so we can call LINQ's Reverse() method on it. With a call to ToArray() the resulting IEnumerable is then again converted to a char array, which is used in the string constructor.
For maximum convenience, we can create an extension method on string to do the reversal: 
static class StringExtensions
{
    public static string Reverse(this string input)
    {
        return new string(input.ToCharArray().Reverse().ToArray());
    }
}
With this class in our code, we can now easily reverse any string: 
Console.WriteLine("hello world".Reverse());

What is Dynamic, Difference between Dynamic and object?

In C# 4.0 microsoft team has introduced this "dynamic" keyword because to achieve dynamically statically typed object which will bypass compile-time checking but during runtime it coverts himself to strong type depending on attached data and do the error-checking. So "dynamic" keyword is called as static type.
Static type language is a language whose type-checking is done at compile time and on the other hand dynamic type language is a language whose type-checking is done at runtime.
Static types : int, string, double, long
Dynamic types : object, arraylist, class objects.
On the compile-time dynamic keyword object acts just like dynamic types i.e. similar like an object but on runtime it gets converts to a strong type depending on the data attached.
Syntax of Dynamic Keyword
class SampleClass{
2
3  dynamic anyobjectname = "test";
4
5}

Class property values cannot be changed once declared  how?

It is possible to create read-only properties. To create a read-only property, we omit the set accessor and provide only the get accessor in the implementation.
using System;

public class Person 
{
    private string _name = "Jane"; 

    public string Name
    {
        get { return _name; }
    }
}

public class ReadonlyProperties
{
    static void Main()
    {
        Person p = new Person();
        // p.Name = "Beky";
        
        Console.WriteLine(p.Name);
    }
}
In the preceding example, we demonstrate the use of a read-only property.
private string _name = "Jane";
We initialize the member right away, because later it is not possible.
public string Name
{
    get { return _name; }
}
We make the property read-only by providing a get accessor only.
// p.Name = "Beky";
This line is now commented. We cannot change the property. If we uncommented the line, the Mono C# compiler would issue the following error: readonly.cs(18,11): error CS0200: Property or indexer `Person.Name' cannot be assigned to (it is read-only).

Is it possible to override a non-virtual method?

No, If a method is virtual, you can override it using the override keyword in the derived class.

 However, non-virtual methods can only hide the base implementation by using the new keyword in place of the override keyword. 

How To Create Text File in C#


string path = @"E:\AppServ\Example.txt";
if (!File.Exists(path))
{
    File.Create(path);
    TextWriter tw = new StreamWriter(path);
    tw.WriteLine("The very first line!");
    tw.Close();
}
else if (File.Exists(path))
{
    TextWriter tw = new StreamWriter(path);
    tw.WriteLine("The next line!");
    tw.Close(); 
}
How To Get Count of .XML files in Main Folder and Under sub folder's
int fileCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length; // Will Retrieve count of all files in directry and sub directries

int fileCount = Directory.GetFiles(path, "*.*", SearchOption.TopDirectory).Length; // Will Retrieve count of all files in directry but not sub directries

int fileCount = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories).Length; // Will Retrieve count of files XML extension in directry and sub directries
Physical Path: "F:/sai/Websites/"
Virtual Path: server.mappath("/Websites")

No comments:

Post a Comment