Showing posts with label .net interview qns. Show all posts
Showing posts with label .net interview qns. Show all posts

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")

asp.net interview Qns

how to bind lakh's of records to gridview with in less time in page load?

You need to implement a server side paging technology. There are two kinds of paging and the client side one gets all the records and then just hides some of them. The server side one only requests the amount of data thats needed for a page from the database. 

Interview questions on session management

difference between inproc and outproc session in asp.net?

 Inproc session mode, 
1. session data is stored in current application domain and so consumes memory of server machine.
2. if server restarts, all session data is lost.
Out-proc mode (which is generally state server),
1. session data is stored on state server and so web servers memory is not consumed.
2. in case of web server restart, session data is preserved.
considering above points, use of session mode is the choice to be made considering load, no. of users, performence requirment etc.
for small web site with limited no. of users, in-proc mode is best suited.
for large applications with huge no. of users, state-server/sql server session mode should be used.   

How to add CSS styles for N'th row  of gridview using jquery in asp.net

Include the latest jquery like:
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
and add the script tag just before closing body section,

    <script type="text/javascript">

        $("#grid tr:nth-child(n)").css("background-color", "Tan");

    </script>
</body>
OR
 $("table.partnerGridClass tbody tr:nth-child(n)").css("background-color", "green")
Ex:- n=1,2...n

How to get id and text value of control using sender in c#

protected void Button1_Click(object sender, EventArgs e)
    {
        if (sender.GetType().ToString().EndsWith("Button"))
        {
            Button btn = (Button)sender;
            string id = btn.ID;
        }
        if (sender.GetType().ToString().EndsWith("TextBox"))
        {
            TextBox txt = (TextBox)sender;
            string id = txt.ID;
        }
        if (sender.GetType().ToString().EndsWith("CheckBox"))
        {
            CheckBox chk = (CheckBox)sender;
            string id = chk.ID;
        }
    }

what is Ispostback() ?

IsPostback property is used to Gets a value that indicates whether the page is being rendered for the first time or is being loaded in response to a postback.

This IsPostBack property returns the boolean value either True or False.

private void Page_Load()
{
    if (!IsPostBack)
    {
        // Validate initially to force asterisks
        // to appear before the first roundtrip.
        BindDropDown();
    }
}
After render the web page, if you do any post back then it will be called. In the web page, we used to check whether its loaded first time or posted back. Because we do not want to bind the concrete controls to rebind again. It will increase the performance of the web application.

Reference: More

What is the difference between custom controls and user controls?

Custom controls are basically compiled code i.e. DLLs. These can be easily added to toolbox, so it can be easily used across multiple projects using drag and drop approach. These controls are comparatively hard to create.
But User Controls (.ascx) are just like pages (.aspx). These are comparatively easy to create but tightly couple with respect to User Interface and code. In order to use across multiple projects, we need to copy and paste to the other project as well.
Reference: b/n Diffrerence