Professional Documents
Culture Documents
Ref Parameter
If 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 Parameter
Generally we will use ref parameters like as shown below
class Program
{
static void Main()
{
int i; // variable need to be initialized
i = 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
Output
*********Output************
13
*********Output************
As we discussed if ref parameter value changed in called method that parameter
value reflected in calling method also
Out Parameter
If you want to pass a variable as out parameter you dont 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 Parameter
Generally we will use out parameters like as shown below
class Program
{
static void Main()
{
int i,j; // No need to initialize variable
Outsample(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 method
When we run above code we will get like as shown below
Output
*********Output************
5
10
*********Output************
String
String 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.
Example
String 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.
Example
sb.Append("test ");
string str = sb.ToString();
Differences
String
StringBuilder
Its an immutable
Its mutable
Index
Only 1 allowed per table physically rearranges the data in the table to confirm to
the index constraints for use on columns that are frequently searched for ranges of
data for use on columns with low selectivity.
Non-Clustered
Index
Up to 249 allowed per table creates a separate list of key values with pointers to
the location of the data in the data pages For use on columns that are searched for
single
values
A clustered index is a special type of index that reorders the way records in the
table are physically stored. Therefore table can have only one clustered index. The
leaf nodes of a clustered index contain the data pages. A non-clustered index is a
special type of index in which the logical order of the index does not match the
physical stored order of the rows on disk. The leaf node of a non-clustered index
does not consist of the data pages. Instead, the leaf nodes contain index rows.
Included
Column
Index
(New
in
SQL
Server
2005)
Can you write the program to find the length of string without using library
function?
Ans: for (int i=0; str[i]!=\n; i++)
{
Count++;
}
What is the difference between scope_identity() and current_identity()?
Ans: Scope_identity and current _identity both are similar and it will return the last
identity value generated in the table.
Scope_Identity will return the identity value in table that is currently in scope
What are difference between GET and POST Methods?
Ans:
GET Method ():
1)
2)
3)
4)
5)
6)
{
get;
set;
}
String FirstName
{
get;
set;
}
String LastName
{
get;
set;
}
Public String GetStudentDetails()
{
// Implementation of Method
}
public String SaveStudentDetails ()
{
// Implementation of Method
}
public abstract String CalculateWage();
}
Interface can only contain the methods declaration and can be implemented in the
class.
As for Example:
Public interface IStudnet
{
String Roll
{
get;
set;
}
String FirstName
{
get;
set;
}
String LastName
{
get;
set;
}
String GetStudentDetails();
String SaveStudentDetails ();
}
Below are the few main difference between Abstract Class and Interface
a. In abstract class method can have definition as well as declaration also. But
Interface should have only definition.
b. All the Methods are Public as default and dont have any access Modifier
Controls in interface, whereas for abstract class we can have access modifier for
methods.
c. Abstract class can have constructor or destructor, whereas interface not.
d. Abstract class cant be part of multiple inheritance and we can implement
multiple interface.
What do you mean by String objects are immutable?
String objects are immutable as its state cannot be modified once created. Every
time when we perform any operation like add, copy, replace, and case conversion or
when we pass a string object as a parameter to a method a new object will be
created.
Example:
String str = "ABC";
str.Replace("A","X");
Here Replace() method will not change data that "str" contains, instead a new
string object is created to hold data "XBC" and the reference to this object is
returned by Replace() method.
So in order to point str to this object we need to write below line.
str = str.Replace("A","X");
Now the new object is assigned to the variable str. earlier object that was assigned
to str will take care by garbage collector as this one is no longer in used.
What is dll hell problem in .NET and how it will solve?
Ans: Dll hell, is kind of conflict that occurred previously, due to the lack of version
supportability of dll for (within) an application
.NET Framework provides operating system with a global assembly cache. This
cache is a repository for all the .net components that are shared globally on a
particular machine. When a .net component installed onto the machine, the global
assembly cache looks at its version, its public key and its language information and
creates a strong name for the component. The component is then registered in the
repository and indexed by its strong name, so there is no confusion between the
different versions of same component, or DLL
What is a Partial class?
Ans: Instead of defining an entire class, you can split the definition into multiple
classes by using partial class keyword. When the application compiled, c# compiler
will group all the partial classes together and treat them as a single class. There are
a couple of good reasons to use partial classes. Programmers can work on different
parts of classes without needing to share same physical file
Ex:
Public partial class employee
{
Public void somefunction()
{
}
}
Public partial class employee
{
Public void function ()
{
}
}
What is difference between constants, read-only and, static?
Constants: The value cant be changed
Read-only: The value will be initialized only once from the constructor of the class.
Static: Value can be initialized once.
What is the cross page post backing?
Asp.Net 2.0 fixed this with built-in features that allowed us to easily send
information from one page to another.
Button control has property PostBackUrl that can be set to URL of any page in our
ASP.Net WebSite where we want to transfer all form values to.
Along with that Asp.Net 2.0 Page class has a property PreviousPage that allows
us to get reference to the Page object that initiated the postback (in other words to
get the actual reference to the Page object of the aspx page on which user clicked
the Submit button on a HTML form).
So for example lets create two sample pages in our Web Application:
SourcePage.aspx
DestinationPage.aspx
In SoucePage in Html form we will put two TextBox controls (one for First Name and
one for Last Name) and one Button component and set its PostBackUrl property to
"~/DestinationPage.aspx".
SourcePage.aspx:
<form id="form1" runat="server">
<div>
First
Name: <asp:TextBox ID="FirstName" runat="server"></asp:TextBox><br /
>
Last
Name: <asp:TextBox ID="LastName" runat="server"></asp:TextBox><br /
><br />
<asp:Button ID="Button1" runat="server" Text="Submit To Destination
Page"PostBackUrl="~/CrossPagePostbacks/DestinationPage.aspx" />
</div>
</form>
When our user clicks the Submit button, all the values from the HTML Form on
SourcePage.aspx will be transfered to the DestinationPage.aspx and we will also be
able to get reference to the SourcePage.aspx in our DestinationPage with
the PreviousPage property like this:
So in our DestinationPage.aspx.cs code-behind we can easily access two TextBox
controls on SourcePage.aspx and show them in two label controls like this:
protected void Page_Load(object sender, EventArgs e)
{
// first check if we had a cross page postback
if ( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack) )
{
Page previousPage = PreviousPage;
TextBox firstName = (TextBox)previousPage.FindControl("FirstName");
TextBox lastName = (TextBox)previousPage.FindControl("LastName");
// we can now use the values from TextBoxes and display them in two
Label controls..
labelFirstName.Text = firstName.Text;
labelLastName.Text = lastName.Text;
}
}
Ans: The difference between application exception and system exception is that
system exceptions are thrown by CLR and application exceptions are thrown by
applications.
What is the difference between authorization and authentication?
Ans: Authorization is a process of allowing or denying resources to particular user
or record
Declaration of authorization is
<authorization>
<allow users=Suresh, Sanjay/>
<deny users=Ramana, Rakesh>
</authorization>
Sometimes authorization allows the unauthorized persons at that time we will use
<deny users=?/>
Authentication means
Authentication is a process where we identify the credentials of user i.e. username,
password and create an identity to mention user as an authenticated.
What is the use of n-tier architecture and 3-tier architecture?
Check this article for 3-tier architecture 3 tier architecture example in asp.net
How to get the version of the assembly?
Ans: lbltxt.text=Assembly. GetExecutingAssembly().GetName().Version.ToString();
What is the location of Global Assembly Cache on the system?
Ans: c:\Windows\assembly
What is the serialization?
Ans: Serialization is a process of converting object into a stream of bites.
What is synchronization?
Ans: The mechanism needed to block one thread access to the data. If the data is
being accessed by another thread.
Synchronization can be accessed by using system.monitor class
A monitor class methods are enter, exit, pulse for this lock statement is also used
Suppose if we need to synchronize some data at that time we need to place that
data in this block
Lock
{
}
Whatever the data has been placed into the lock block that data has been blocked
your browser knows what IP to use, it will connect to the appropriate webserver
and ask for the page. The webserver then returns the requested page and your
browser renders it to the screen.
The firewall will control connections to & from your computer. For the most part it
will just be controlling who can connect to your computer and on what ports. For
web browsing your firewall generally won't be doing a whole lot.
Your router (see http://en.wikipedia.org/wiki/Router ) essentially guides your
request through the network, helping the packets get from computer to computer
and potentially doing some NAT (seehttp://en.wikipedia.org/wiki/Network_add ) to
translate IP addresses along the way (so your internat LAN request can be
transitioned onto the wider internet and back).
IP Addresses (see http://en.wikipedia.org/wiki/IP_address ) are unique addresses for
computers that basically allow computers to find each other. Think of the IP address
as a computer's well address or phone number, you've got to know someone's
phone number before you can call them and you've got to know a computer's IP
address before you can connect to it. Going back to the start - that's what those
URLS and DNS make possible, you don't know John Doe's phone number so you
look in the phone book; likewise your computer doesn't know yahoo.com's IP
address so it looks in DNS.
To create destructor we need to create method in a class with same name as class
preceded with ~ operator.
Syntax of Destructor
class 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
{
// Constructor
public 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 below
Output
An instance created
An instance destroyed
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
{
Welcome to Aspdotnet-Suresh
In 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.
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. If you want to know
more about constructors check this article constructors in c#.
Static Constructor
When we declared constructor as static it will be invoked only once for any number
of instances of the class and its 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 instance
Sample obj=new Sample();
Console.WriteLine(obj.param1 + " " + obj.param2);
// Here only instance constructor will be invoked
Sample obj1 = new Sample();
Console.WriteLine(obj1.param1 +" " + obj1.param2);
Console.ReadLine();
}
}
}
When we run above program we will get output like as shown below
Output
Static Constructor
Sample Instance Constructor
Sample Instance Constructor
Importance 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.
class SampleA
{
public SampleA()
{
Console.WriteLine("Sample A Test Method");
}
}
Types of Constructors
Basically constructors are 5 types those are
1.
2.
3.
4.
5.
Default Constructor
Parameterized Constructor
Copy Constructor
Static Constructor
Private Constructor
Default Constructor
A 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 below
using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample()
// Default Constructor
{
param1 = "Welcome";
param2 = "Aspdotnet-Suresh";
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample(); // Once object of class created automatically constructor will be
called
Console.WriteLine(obj.param1);
Console.WriteLine(obj.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below
Output
Welcome
Aspdotnet-Suresh
Parameterized Constructors
A 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 below
using 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","Aspdotnet-Suresh"); // Parameterized Constructor
Called
Console.WriteLine(obj.param1 +" to "+ obj.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below
Output
Welcome to Aspdotnet-Suresh
Constructor Overloading
In c# we can overload constructor by creating another constructor with same
method name and different parameters like as shown below
using 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 Called
Sample obj1=new Sample("Welcome","Aspdotnet-Suresh"); // Parameterized Constructor will
Called
Console.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 below
Output
Copy Constructor
using 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", "Aspdotnet-Suresh"); // Create instance to class
Sample
Sample obj1=new Sample(obj); // Here obj details will copied to obj1
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below
Output
Welcome to Aspdotnet-Suresh
Static Constructor
When we declared constructor as static it will be invoked only once for any number
of instances of the class and its 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 instance
Sample obj=new Sample();
Console.WriteLine(obj.param1 + " " + obj.param2);
// Here only instance constructor will be invoked
Sample obj1 = new Sample();
Console.WriteLine(obj1.param1 +" " + obj1.param2);
Console.ReadLine();
}
}
}
When we run above program we will get output like as shown below
Output
Static Constructor
Sample Instance Constructor
Sample Instance Constructor
Importance 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 Constructor
using System;
namespace ConsoleApplication3
{
public class Sample
{
public string param1, param2;
public Sample(string a,string b)
{
param1 = a;
param2 = b;
}
Welcome to Aspdotnet-Suresh
In 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.
using System;
namespace ConsoleApplication3
{
class SampleA
{
public void Show()
{
Console.WriteLine("Sample A Test Method");
}
}
class SampleB:SampleA
{
public void Show()
{
Console.WriteLine("Sample B Test Method");
}
}
class Program
{
static void Main(string[] args)
{
SampleA a=new SampleA();
SampleB b=new SampleB();
a.Show();
b.Show();
a = new SampleB();
a.Show();
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below but with some warning
message inSampleB.Show() method like new keyword is required in Show because it hides
method in base classSampleA.Show()
Output
using System;
namespace ConsoleApplication3
{
class SampleA
{
public void Show()
{
Console.WriteLine("Sample A Test Method");
}
}
class SampleB:SampleA
{
public new void Show()
{
Console.WriteLine("Sample B Test Method");
}
}
class Program
{
static void Main(string[] args)
{
SampleA a=new SampleA();
SampleB b=new SampleB();
a.Show();
b.Show();
a = new SampleB();
a.Show();
Console.ReadLine();
}
}
}
Virtual and Override Keywords Example or Method Overriding
In method overriding we can override a method in base class by creating similar method in
derived class this can be achieved by using inheritance principle and using
virtual & override keywords. If we want to override base class method then we need to
declare base class method with virtual keyword and the method which we created in
derived class to override base class need to declare with override keyword like as shown
below
using System;
namespace ConsoleApplication3
{
class SampleA
{
public virtual void Show()
{
Console.WriteLine("Sample A Test Method");
}
}
class SampleB:SampleA
{
public override void Show()
{
Console.WriteLine("Sample B Test Method");
}
}
class Program
{
static void Main(string[] args)
{
SampleA a=new SampleA();
SampleB b=new SampleB();
a.Show();
b.Show();
a = new SampleB();
a.Show();
Console.ReadLine();
}
}
}
When we run above program we will get output like as shown below
Output
We can use both method hiding and method overriding by using virtual and new keyword at
that time derived class method can be declared with virtual and new like as shown below
using System;
namespace ConsoleApplication3
{
class SampleA
{
public void Show()
{
Console.WriteLine("Sample A Test Method");
}
}
class SampleB:SampleA
{
public new virtual void Show()
{
Console.WriteLine("Sample B Test Method");
}
}
class SampleC : SampleB
{
public override void Show()
{
Console.WriteLine("Sample C Test Method");
}
}
class Program
{
static void Main(string[] args)
{
SampleA a=new SampleA();
SampleB b=new SampleB();
SampleB c = new SampleC();
a.Show();
b.Show();
c.Show();
a = new SampleB();
a.Show();
b = new SampleC();
b.Show();
Console.ReadLine();
}
}
}
Output
Sample
Sample
Sample
Sample
Sample
A
B
C
A
C
Test
Test
Test
Test
Test
Method
Method
Method
Method
Method
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
DelegatSample delgate1 = sc.Add;
int i = delgate1(10, 20);
Console.WriteLine(i);
DelegatSample delgate2 = sc.Sub;
int j = delgate2(20, 10);
Console.WriteLine(j);
}
}
Output
Whenever we run above code we will get output like as shown below
Add Result : 30
Sub Result : 10
What is the use of Delegates?
Suppose if you have multiple methods with same signature (return type & number
of parameters) and want to call all the methods with single object then we can go
for delegates.
Delegates are two types
- Single Cast Delegates
- Multi Cast Delegates
Single Cast Delegates
Single cast delegate means which hold address of single method like as explained in
above example.
Multicast Delegates
Multi cast delegate is used to hold address of multiple methods in single delegate.
To hold multiple addresses with delegate we will use overloaded += operator and if
you want remove addresses from delegate we need to use overloaded operator -=
Multicast delegates will work only for the methods which have return type only void.
If we want to create a multicast delegate with return type we will get the return
type of last method in the invocation list
Check below sample code for delegate declaration and methods declaration
Whenever we run above code we will get output like as shown below
Addition Value : 15
Subtraction Value : 5
Multiply Value : 50
C# - Early Binding and Late Binding with Example & Difference b/w Early &
Late Binding
Polymorphism
Polymorphism means many forms (ability to take more than one form). In
Polymorphism poly means multiple and morph means forms so polymorphism
means many forms.
In polymorphism we will declare methods with same name and different parameters
in same class or methods with same name and same parameters in different
classes. Polymorphism has ability to provide different implementation of methods
that are implemented with same name.
Arrays
Arrays 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 Arrays
Generally we will declare arrays with fixed length and store values like as shown below
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
namespace
Declaration of Arraylist
To know how to declare and store values in array lists check below code
ArrayLists
Array Lists are not strong type collection and size
will increase or decrease dynamically
Const:
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.
Example
public 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;
}
}