C# Interview Questions for Freshers and experienced....
What is sealed class in c#?
- Generally if we create classes we can inherit the properties of that created class in any class without having any restrictions. In some situation we will get requirement like we don’t want to give permission for the users to derive the classes from it or don’t allow users to inherit the properties from particular class in that situations what we can do?
- Example to declare class as sealedsealed class Test{public int Number;public string Name;}If the class declared with an access modifier, the Sealed keyword can appear after or before the public keyword.
What is the difference between array and arraylist in c#?
- ArraysArrays are strongly typed collection of same datatype and these arrays are fixed length that cannot be changed during runtime. Generally in arrays we will store values with index basis that will start with zero. If we want to access values from arrays we need to pass index values.Declaration of ArraysGenerally we will declare arrays with fixed length and store values like as shown belowstring[] arr=new string[2];arr[0] = "welcome";arr[1] = "Aspdotnet-suresh";In above code I declared array size 2 that means we can store only 2 string values in array.Arraylists
- Array lists are not strongly type collection. It will store values of different datatypes or same datatype. Array list size will increase or decrease dynamically it can take any size of values from any data type. These Array lists will be accessible with “System.Collections” namespaceDeclaration of ArraylistTo know how to declare and store values in array lists check below codeArrayList strarr = new ArrayList();strarr.Add("welcome"); // Add string valuesstrarr.Add(10); // Add integer valuesstrarr.Add(10.05); // Add float valuesIf you observe above code I haven’t mentioned any size in array list we can add all the required data there is no size limit and we will use add method to bind values to array list.
What is using statement in c#?
- Generally in our applications we will write code like create connection object to handle connectionstring after that open a connection and create command object etc. to interact with database to get data that would be like thisSqlConnection con = new SqlConnection(connectionString);con.Open();SqlCommand cmd = new SqlCommand (commandString, con);cmd.ExecuteNonQuery();con.Close();It’s very easy way to write above code but problem is SqlConnection and SqlCommand objects will create IDISPOSABLE interface that means it could create unmanaged resources in our application to cleanup those objects we need to call Dispose() method at the end of our process otherwise those objects will remain in our application.Suppose we use using statement in our applications it will automatically create try / finally blocks for the objects and automatically runs Dispose() method for us no need to create any try/finally block and no need to run any Dispose() method.If we use using statement we need to write code will be like thisC# Codeusing (SqlConnection con = new SqlConnection(connectionString)){using (SqlCommand cmd = new SqlCommand (commandString, con)){con.Open();cmd.ExecuteNonQuery();}}
What is the difference between constantand readonly in c#?
- Const:1. Const can only be initialized at the time of declaration of the field.2. Const values will evaluate at compile time only.3. Const value can’t be changed these will be same at all the time.4. This type of fields are required when one of the field values remains constant throughout the system like Pi will remain same in your Maths Class.
- Read-only:1. The value will be initialized either declaration time or the constructor of the class allowing you to pass the value at run time.2. Read only values will evaluate at runtime only.Examplepublic class Const_VS_Readonly{public const int I_CONST_VALUE = 2;public readonly int I_RO_VALUE;public Const_VS_Readonly(){I_RO_VALUE = 3;}}
What is the difference between dispose and finalize methods in c#?
- Dispose() Method- This dispose method will be used to free unmanaged resources like files, database connection etc.- To clear unmanaged resources we need to write code manually to raise dispose() method.- This Dispose() method belongs to IDisposable interface.- If we need to implement this method for any custom classes we need to inherit the class from IDisposable interface.- It will not show any effect on performance of website and we can use this method whenever we want to free objects immediately.Example//Implement Dispose Method.public class TestDispose : IDisposable{private bool disposed = false;
- /Implement IDisposable.public void Dispose(){Dispose(true);}protected virtual void Dispose(bool disposing){if (!disposed){if (disposing){// clean unmanged objects}// clean unmanaged objects).disposed = true;}}}Finalize() Method- This method also free unmanaged resources like database connections, files etc…- It is automatically raised by garbage collection mechanism whenever the object goes out of scope.- This method belongs to object class.- We need to implement this method whenever we have unmanaged resources in our code and make sure these resources will be freed when garbage collection process done.- It will show effect on performance of website and it will not suitable to free objects immediately.Example// Implementing Finalize methodpublic class Sample{//At runtime destructor automatically Converted to Finalize method.~Sample(){// your clean up code}}
What is the difference between ref and out parameters in c#?
- Ref ParameterIf you want to pass a variable as ref parameter you need to initialize it before you pass it as ref parameter to method. Ref keyword will pass parameter as a reference this means when the value of parameter is changed in called method it get reflected in calling method also.Declaration of Ref ParameterGenerally we will use ref parameters like as shown belowint i=3; // variable need to be initializedRefsample(ref i);If you observe above code first we declared variable and initialized with value 3 before it pass a ref parameter to Refsample methodExampleclass Program{static void Main(){int i; // variable need to be initializedi = 3;Refsample(ref i);Console.WriteLine(i);}public static void Refsample(ref int val1){val1 += 10;}}When we run above code we will get like as shown below
- Output13As we discussed if ref parameter value changed in called method that parameter value reflected in calling method alsoOut ParameterIf you want to pass a variable as out parameter you don’t need to initialize it before you pass it as out parameter to method. Out keyword also will pass parameter as a reference but here out parameter must be initialized in called method before it return value to calling method.Declaration of Out ParameterGenerally we will use out parameters like as shown belowint i,j; // No need to initialize variableOutsample(out i, out j);If you observe above code first we declared variable and we it pass a out parameter to Outsamplemethod without initialize the values to variablesExampleclass Program{static void Main(){int i,j; // No need to initialize variableOutsample(out i, out j);Console.WriteLine(i);Console.WriteLine(j);}public static int Outsample(out int val1, out int val2){val1 = 5;val2 = 10;return 0;}}If we observe code we implemented as per our discussion like out parameter values must be initialized in called method before it return values to calling methodWhen we run above code we will get like as shown belowOutput510
What is the difference between string and stringbuilder in c#?
- StringString is immutable. Immutable means once we create string object we cannot modify. Any operation like insert, replace or append happened to change string simply it will discard the old value and it will create new instance in memory to hold the new value.Examplestring str = "hi";// create a new string instance instead of changing the old onestr += "test";str += "help";String BuilderString builder is mutable it means once we create string builder object we can perform any operation like insert, replace or append without creating new instance for every time.
- ExampleStringBuilder sb = new StringBuilder("");sb.Append("hi");sb.Append("test ");string str = sb.ToString();DifferencesStringStringBuilderIt’s an immutableIt’s mutablePerformance wise string is slow because every time it will create new instancePerformance wise stringbuilder is high because it will use same instance of object to perform any actionIn string we don’t have append keywordIn StringBuilder we can use append keywordString belongs to System namespaceStringbuilder belongs to System.Text namespace
What is the difference between throw and throw ex in c#?
- ThrowIn Throw, the original exception stack trace will be retained. To keep the original stack trace information, the correct syntax is 'throw' without specifying an exception.Declaration of throwtry{// do some operation that can fail}catch (Exception ex){// do some local cleanupthrow;}
- Throw ex
- In Throw ex, the original stack trace information will get override and you will lose the original exception stack trace. I.e. 'throw ex' resets the stack trace.Declaration of throw extry{// do some operation that can fail}catch (Exception ex){// do some local cleanupthrow ex;}}
What is destructor in c#?
- To create destructor we need to create method in a class with same name as class preceded with ~ operator.Syntax of Destructorclass SampleA{public SampleA(){// Constructor}~SampleA(){// Destructor}}
- Example of Destructor
- In below example I created a class with one constructor and one destructor. An instance of class is created within a main function. As the instance is created within the function, it will be local to the function and its life time will be expired immediately after execution of the function was completed.using System;namespace ConsoleApplication3{class SampleA{// Constructorpublic SampleA(){Console.WriteLine("An Instance Created");}// Destructor~SampleA(){Console.WriteLine("An Instance Destroyed");}}class Program{public static void Test(){SampleA T = new SampleA(); // Created instance of class}static void Main(string[] args){Test();GC.Collect();Console.ReadLine();}}}When we run above program it will show output like as shown belowOutputAn instance createdAn instance destroyed
What is constructor in c#?
- Constructor is a special method of a class which will invoke automatically whenever instance or object of class is created. Constructors are responsible for object initialization and memory allocation of its class. If we create any class without constructor, the compiler will automatically create one default constructor for that class. There is always at least one constructor in every class.Here you need to remember that a class can have any number of constructors and constructors don’t have any return type, not even void and within a class we can create only one static constructor.Generally constructor name should be same as class name. If we want to create constructor in a class we need to create a constructor method name same as class name check below sample method for constructorclass SampleA{public SampleA(){Console.WriteLine("Sample A Test Method");}}Types of ConstructorsBasically constructors are 5 types those are1. Default Constructor2. Parameterized Constructor3. Copy Constructor4. Static Constructor5. Private ConstructorDefault ConstructorA constructor without having any parameters called default constructor. In this constructor every instance of the class will be initialized without any parameter values like as shown belowusing System;namespace ConsoleApplication3{class Sample{public string param1, param2;public Sample() // Default Constructor{param1 = "Welcome";param2 = "C# .Net Code";}}class Program{static void Main(string[] args){Sample obj=new Sample(); // Once object of class created automatically constructor will be calledConsole.WriteLine(obj.param1);Console.WriteLine(obj.param2);Console.ReadLine();}}}When we run above program it will show output like as shown belowOutputWelcomeC# .Net CodeParameterized ConstructorsA constructor with at least one parameter is called as parameterized constructor. In parameterized constructor we can initialize each instance of the class to different values like as shown belowusing System;namespace ConsoleApplication3{class Sample{public string param1, param2;public Sample(string x, string y) // Declaring Parameterized constructor with Parameters{param1 = x;param2 = y;}}class Program{static void Main(string[] args){Sample obj=new Sample("Welcome","C# .Net Code"); // Parameterized Constructor CalledConsole.WriteLine(obj.param1 +" to "+ obj.param2);Console.ReadLine();}}}When we run above program it will show output like as shown belowOutputWelcome to C# .Net CodeConstructor OverloadingIn c# we can overload constructor by creating another constructor with same method name and different parameters like as shown belowusing System;namespace ConsoleApplication3{class Sample{public string param1, param2;public Sample() // Default Constructor{param1 = "Hi";param2 = "I am Default Constructor";}public Sample(string x, string y) // Declaring Parameterized constructor with Parameters{param1 = x;param2 = y;}}class Program{static void Main(string[] args){Sample obj = new Sample(); // Default Constructor will CalledSample obj1=new Sample("Welcome","C# .Net Code"); // Parameterized Constructor will CalledConsole.WriteLine(obj.param1 + ", "+obj.param2);Console.WriteLine(obj1.param1 +" to " + obj1.param2);Console.ReadLine();}}When we run above program it will show output like as shown belowOutputHi, I am Default ConstructorWelcome to C# .Net CodeCopy ConstructorA parameterized constructor that contains a parameter of same class type is called as copy constructor. Main purpose of copy constructor is to initialize new instance to the values of an existing instance. Check below example for thisusing System;namespace ConsoleApplication3{class Sample{public string param1, param2;public Sample(string x, string y){param1 = x;param2 = y;}public Sample(Sample obj) // Copy Constructor{param1 = obj.param1;param2 = obj.param2;}}class Program{static void Main(string[] args){Sample obj = new Sample("Welcome", "C# .Net Code"); // Create instance to class SampleSample obj1=new Sample(obj); // Here obj details will copied to obj1Console.WriteLine(obj1.param1 +" to " + obj1.param2);Console.ReadLine();}}}When we run above program it will show output like as shown belowOutputWelcome to C# .Net CodeStatic ConstructorWhen we declared constructor as static it will be invoked only once for any number of instances of the class and it’s during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.using System;namespace ConsoleApplication3{class Sample{public string param1, param2;static Sample(){Console.WriteLine("Static Constructor");}public Sample(){param1 = "Sample";param2 = "Instance Constructor";}}class Program{static void Main(string[] args){// Here Both Static and instance constructors are invoked for first instanceSample obj=new Sample();Console.WriteLine(obj.param1 + " " + obj.param2);// Here only instance constructor will be invokedSample obj1 = new Sample();Console.WriteLine(obj1.param1 +" " + obj1.param2);Console.ReadLine();}}}When we run above program we will get output like as shown belowOutputStatic ConstructorSample Instance ConstructorSample Instance ConstructorImportance points of static constructor- Static constructor will not accept any parameters because it is automatically called by CLR.- Static constructor will not have any access modifiers.- Static constructor will execute automatically whenever we create first instance of class- Only one static constructor will allowed.Private ConstructorPrivate constructor is a special instance constructor used in a class that contains static member only. If a class has one or more private constructor and no public constructor then other classes is not allowed to create instance of this class this mean we can neither create the object of the class nor it can be inherit by other class. The main purpose of creating private constructor is used to restrict the class from being instantiated when it contains every member as static.using System;namespace ConsoleApplication3{public class Sample{public string param1, param2;public Sample(string a,string b){param1 = a;param2 = b;}private Sample() // Private Constructor Declaration{Console.WriteLine("Private Constructor with no prameters");}}class Program{static void Main(string[] args){// Here we don't have chance to create instace for private constructorSample obj = new Sample("Welcome","to C# .Net Code");Console.WriteLine(obj.param1 +" " + obj.param2);Console.ReadLine();}}}OutputWelcome to C# .Net CodeIn above method we can create object of class with parameters will work fine. If create object of class without parameters it will not allow us create.// it will works fineSample obj = new Sample("Welcome","to C# .Net Code");// it will not work because of inaccessabilitySample obj=new Sample();Important points of private constructor- One use of private construct is when we have only static member.- Once we provide a constructor that is either private or public or any, the compiler will not allow us to add public constructor without parameters to the class.- If we want to create object of class even if we have private constructors then we need to have public constructor along with private constructor.
What is the difference between array and arraylist in c#?
What is the difference between array and arraylist in c#?
What is the difference between array and arraylist in c#?
What is the difference between array and arraylist in c#?
What is the difference between array and arraylist in c#?
What is the difference between array and arraylist in c#?
What is the difference between array and arraylist in c#?
Reference - aspdotnet-suresh
No comments:
Post a Comment