Ans.A static class is a class which can not be instantiated using the ‘new’ keyword. They also only contain static members,are sealed and have a private constructor.
Static classes are classes that contain only static members.A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword
to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. For example, if you have a static class that is named UtilityClass that has a public method named MethodA, you call the method as shown in the following example:
UtilityClass.MethodA();
A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields. For example, in the .NET Framework Class Library, the static System.Math class contains methods that perform mathematical operations,without any requirement to store or retrieve data that is unique to a particular instance of the Math class. That is, you apply the members of the class by specifying the class name and the method name, as shown in the following example.
public static class TemperatureConverter
{
public static double CelsiusToFahrenheit(string temperatureCelsius)
{
// Convert argument to double for calculations.
double celsius = Double.Parse(temperatureCelsius);
// Convert Celsius to Fahrenheit.
double fahrenheit = (celsius * 9 / 5) + 32;
return fahrenheit;
}
public static double FahrenheitToCelsius(string temperatureFahrenheit)
{
// Convert argument to double for calculations.
double fahrenheit = Double.Parse(temperatureFahrenheit);
// Convert Fahrenheit to Celsius.
double celsius = (fahrenheit - 32) * 5 / 9;
return celsius;
}
}
class TestTemperatureConverter
{
static void Main()
{
Console.WriteLine("Please select the convertor direction");
Console.WriteLine("1. From Celsius to Fahrenheit.");
Console.WriteLine("2. From Fahrenheit to Celsius.");
Console.Write(":");
string selection = Console.ReadLine();
double F, C = 0;
switch (selection)
{
case "1":
Console.Write("Please enter the Celsius temperature: ");
F = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());
Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
break;
case "2":
Console.Write("Please enter the Fahrenheit temperature: ");
C = TemperatureConverter.FahrenheitToCelsius(Console.ReadLine());
Console.WriteLine("Temperature in Celsius: {0:F2}", C);
break;
default:
Console.WriteLine("Please select a convertor.");
break;
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
/* Example Output:
Please select the convertor direction
1. From Celsius to Fahrenheit.
2. From Fahrenheit to Celsius.
:2
Please enter the Fahrenheit temperature: 20
Temperature in Celsius: -6.67
Press any key to exit.
*/
The following list provides the main features of a static class:
- Contains only static members.
- Cannot be instantiated.
- Is sealed.
- Cannot contain Instance Constructors.
There are few limitations for static classes
- It can only contain static members (members explicitly marked with keyword ‘static’)
- It can not be instantiated
- It is sealed by default (i.e., it can not be inherited)
- It can not contain a constructor (although it may have a static constructor)
The static classes might be useful when we want a class which can not be instantiated or which should only be initiated once (Singleton class).
We may achieve the same functionality by declaring all members in ordinary class as static and making its constructor private. But when using
static classes, compiler ensures that none of the member of its members is non-static (i.e., all members are static).
2. What is static member?
Ans.A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.
It is more typical to declare a non-static class with some static members, than to declare an entire class as static. Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.
Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.
Although a field cannot be declared as static const, a const field is essentially static in its behavior. It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the same ClassName.MemberName notation that is used for static fields. No object instance is required.
C# does not support static local variables (variables that are declared in method scope).
You declare static class members by using the static keyword before the return type of the member, as shown in the following example:
public class Automobile
{
public static int NumberOfWheels = 4;
public static int SizeOfGasTank
{
get
{
return 15;
}
}
public static void Drive() { }
public static event EventType RunOutOfGas;
// Other non-static fields and properties...
}
Static members are initialized before the static member is accessed for the first time and before the static constructor, if there is one, is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member, as shown in the following example:
Automobile.Drive();
int i = Automobile.NumberOfWheels;
If your class contains static fields, provide a static constructor that initializes them when the class is loaded.
A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for a null object references. However, most of the time the performance difference between the two is not significant.
The C# provides a special type of constructor known as static constructor to initialize the static data members when the class is loaded at first. Remember
that, just like any other static member functions, static constructors can't access non-static data members directly.
The name of a static constructor must be the name of the class and even they don't have any return type. The keyword static is used to differentiate the
static constructor from the normal constructors. The static constructor can't take any arguments. That means there is only one form of static constructor,
without any arguments. In other way it is not possible to overload a static constructor.
We can't use any access modifiers along with a static constructor.
// C# static constructor
// Author: rajeshvs@msn.com
using System;
class MyClass
{
public static int x;
public static int y;
static MyClass ()
{
x = 100;
Y = 200;
}
}
class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y);
}
}
Note that static constructor is called when the class is loaded at the first time. However we can't predict the exact time and order of static constructor
execution. They are called before an instance of the class is created, before a static member is called and before the static constructor of the derived class
is called.
3. What is static function?
Ans.A static function is another term for a static method. It allows you to execute the function without creating an instance of its defining class.
They are similar to global functions. An example of a static function could be: ConvertFromFarenheitToCelsius with a signature as follows:
public static double ConvertFromFarenheitToCelsius (string valToConvert)
{
//add code here
}
Inside a C# class, member functions can also be declared as static. But a static member function can access only other static members. They can access non-static
members only through an instance of the class.
We can invoke a static member only through the name of the class. In C#, static members can't invoked through an object of the class as like in C++ or JAVA.
// C#:static & non-static
// Author: rajeshvs@msn.com
using System;
class MyClass
{
private static int x = 20;
private static int y = 40;
public static void Method()
{
Console.WriteLine("{0},{1}",x,y);
}
}
class MyClient
{
public static void Main()
{
MyClass.Method();
}
}
4. What is static constructor?
Ans.A static constructor has a similar function as a normal constructor i.e. it is automatically called the first time a class is loaded. The differences between
a conventional constructor are that it cannot be overloaded, cannot have any parameters nor have any access modifiers and must be preceded by the
keyword static. In addition, a class with a static constructor may only have static members.
5. How can we inherit a static variable?
6. How can we inherit a static member?
Ans. of 5 & 6
When inheriting static members there is no need to instantiate the defining class using the ‘new’ keyword.
public class MyBaseClass
{
MyBaseClass()
{
}
public static void PrintName()
{
}
}
public class MyDerivedClass : MyBaseClass
{
MyDerivedClass ()
{
public void DoSomething()
{
MyBaseClass.GetName();
}
}
}
7. Can we use a static function with a non-static variable?Ans.No.
8. How can we access static variable?
Ans.
By employing the use of a static member field as follows:
public class CashSales
{
//declare static member field
private static int maxUnitsAllowed = 50;
//declare method to return maximum number of units allowed
public static int GetMaxUnitsAllowed ()
{
Return maxUnitsAllowed;
}
}
The static field can now be accessed by simply doing CashSales.GetMaxUnitsAllowed(). No need to create an instance of the class.9. Why main function is static?
Ans.Because it is automatically loaded by the CLR and initialised by the runtime when the class is first loaded. If it wasn’t static an instance of
the class would first need to be created and initialised.
10. How will you load dynamic assembly? How will create assesblies at run time?
Ans.
Load assembly:
By using classes from the System.Reflection namespace.
Assembly x = Assembly.LoadFrom( “LoadMe.dll” );
Create assembly;
Use classes from System.CodeDom.Compiler;
11. What is Reflection?
Ans.The System.Reflection namespace provides us with a series of classes that allow us to interrogate the codebase at run-time and perform functions
such as dynamically load assemblies, return property info e.t.c.
12. If I have more than one version of one assemblies, then how will I use old version (how/where to specify version number?) in my application?
Ans.The version number is stored in the following format: …. The assembly manifest can then contain a reference to which version number we want to use.
13. How do you create threading in.NET? What is the namespace for that?
Ans.
System.Threading;
//create new thread using the thread class’s constructor
Thread myThread = new Thread(new ThreadStart (someFunction));
14. What do you mean by Serialize and MarshalByRef?
Ans.
Serialization is the act of saving the state of an object so that it can be recreated (i.e deserialized) at a later date.
The MarshalByRef class is part of the System.Runtime.Remoting namespace and enables us to access and use objects that reside in different application
domains. It is the base class for objects that need to communicate across application domains. MarshalByRef objects are accessed directly within their own
application domain by using a proxy to communicate. With MarshalByValue the a copy of the entire object is passed across the application domain
15. What is the difference between Array and LinkedList?
Ans.An array is a collection of the same type. The size of the array is fixed in its declaration.
A linked list is similar to an array but it doesn’t have a limited size.
16. What is Asynchronous call and how it can be implemented using delegates?
Ans.
A synchronous call will wait for a method to complete before program flow is resumed. With an asynchronous call the program flow continues whilst the method executes.
//create object
SomeFunction objFunc = new SomeFunction();
//create delegate
SomeDelegate objDel = new SomeDelegate(objFunc.FunctionA);
//invoke the method asynchronously (use interface IAsyncResult)
IAsyncResult asynchCall = SomeDelegate.Invoke();
17. How to create events for a control? What is custom events? How to create it?
Ans.
An event is a mechanism used in a class that can be used to provide a notification when something interesting happens. (typical evens in a windows application
include: change text in textbox, double click or click a button, select an item in dropdown box).
A custom event is an event created by the user that other developers can use. For example assuming that we have a CashTransaction class and we have a bank
balance property in that class. We may want to set-up an event that provides a notification when the bank balance drops below a certain amount. In order to
produce an event the process would be roughly as follows:
Create the class for the event derived from EventArgs.
Create a delegate with a return type of void.
Create a class containing the method that will activate the event.
Create a class with methods to handle the event.
18. If you want to write your own dot net language, what steps you will you take care?
Ans.We will need to ensure that the high level code is compiled to MSIL (Microsoft intermediate language) so that it can be interpreted by the CLR.
19. Describe the diffeerence between inline and code behind - which is best in a loosely coupled solution?
Ans.
The term ‘code behind’ refers to application code that is not embedded within the ASPX page and is separated out into a separate file which is then referenced
from the ASPX page. Inline code is the traditional ASP architectural model where business logic code was embedded within the ASP page. Separating the business
logic code from the presentation layer offers several advantages:
1) It allows graphic designers and web developers to work on the presentation layer whilst the application developers concentrate on the business logic.
2) The codebehind file is compiled as a single dll increasing the efficiency of the application,
3) The codebehind model offers a true OO development platform,
4) It speeds up development time as it allows developers to fully maximise the features of the .NET framework such as Cahing, ViewState, Session, Smart Navigation etc.
5) Code is much easier to maintain and susceptible for change.
6) The compiler and VS.NET provides much better support for error checking, intellisense and debugging when using the code behind model.
20. How dot net compiled code will become platform independent?
Ans.
The raison d’etre for .NET was to cater for multiples languages on a single windows platform whereas the aim of Java was to be a single language on multiple
platforms. The only way that .NET can be platform independent is if there is a version of the .NET framework installed on the target machine.
21. Without modifying source code if we compile again, will it be generated MSIL again?
Ans.No.
22. How does you handle this COM components developed in other programming languages in.NET?
Ans.
use TlbImp.exe to import the COM types into your .NET project. If no type library for the COM component then use System.Runtime.InteropServices
use RegAsm.exe to call a .NET developed component in a COM application.
23. How CCW (Com Callable Wrapper) and RCW (Runtime Callable Wrappers) works?
Ans.
CCW: When a COM application calls a NET object the CLR creates the CCW as a proxy since the COM application is unable to directly access the .NET object.
RCW: When a .NET application calls a COM object the CLR creates the RCW as a proxy since the .NET application is unable to directly access the .COM object.
24. What are the new thee features of COM+ services, which are not there in COM (MTS)?
Ans.
Role based security.
Neutral apartment threading.
New environment called context which defines the execution environment
25. What are the differences between COM architecture and.NET architecture?
Ans.
.Net architecture has superseded the old COM architecture providing a flexible rapid application development environment which can be used to create windows,
web and console applications and web services. .NET provides a powerful development environment that can be used to create objects in any .NET compliant language.
.NET addresses the previous problems of dll hell with COM by providing strongly named assemblies and side-by-side execution where two assemblies with the same name can run on the same box.
26. Can we copy a COM dll to GAC folder?
Ans.
No. It only stores .NET assemblies.
27. What is Shared and Repeatable Inheritance?
Ans.
28. Can you explain what inheritance is and an example of when you might use it?
Ans.
Inheritance is a fundamental feature of any OO language. It allows us to inherit the members and attributes from a base class to a new derived class. This
leads to increased code reusability and also makes applications easier to develop, maintain and extend as the new derived class can contain new features not
available in the base class whilst at the same time preserving the attributes inherited from the base class.
29. How can you write a class to restrict that only one object of this class can be created (Singleton class)?
Ans.
Use the singleton design pattern.
public sealed class Singleton
{
static readonly Singleton Instance=new Singleton();
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return Instance;
}
}
}
30. What are virtual destructures?Ans.
A constructor can not be virtual but a destructor may. Use virtual destructors when you want to implement polymorphic tearing down of an object.
31. What is close method? How its different from Finalize and Dispose?
Ans.
finalise is the process that allows the garbage collector to clean up any unmanaged resources before it is destroyed.
The finalise method can not be called directly; it is automatically called by the CLR. In order to allow more control over the release of unmanaged resources
the .NET framework provides a dispose method which unlike finalise can be called directly by code.
Close method is same as dispose. It was added as a convenience.
32. What is Boxing and UnBoxing?
Ans.
Boxing is the process of converting a value type to a reference type. More specifically it involves encapsulating a copy of the object and moving it from
stack to heap. Unboxing is the reverse process.
33. What is check/uncheck?
Ans.
checked: used to enable overflow checking for arithmetic and conversion functions.
unchecked: used to disable overflow checking for arithmetic and conversion functions
34. What is the use of base keyword? Tell me a practical example for base keyword’s usage?
Ans.
The base keyword is used to access members of the base class from within a derived class:
* Call a method on the base class that has been overridden by another method.
* Specify which base-class constructor should be called when creating instances of the derived class.
A base class access is permitted only in a constructor, an instance method, or an instance property accessor.
It is an error to use the base keyword from within a static method.
Example:In this example, both the base class, Person, and the derived class, Employee, have a method named Getinfo. By using the base keyword,
it is possible to call the Getinfo method on the base class, from within the derived class.
// keywords_base.cs
// Accessing base class members
using System;
public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";
public virtual void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}
class Employee: Person
{
public string id = "ABC567EFG";
public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Employee ID: {0}", id);
}
}
class TestClass {
public static void Main()
{
Employee E = new Employee();
E.GetInfo();
}
}
35. What are the different.NET tools which you used in projects?Ans:Just read your question once again and thought Interviewer might be asking about the development tool you have used to develop ASP.NET projects.
So your answer can be Visual Studio 2005 or 2008 or 2010 whatever you have used, you may also tell Visual Web Developer or any other tool you might
have used to develop your ASP.NET Projects
Remaining answers coming soon
36. What happens when you try to update data in a dataset in.NET while the record is already deleted in SQL Server as backend?
37. What is concurrency? How will you avoid concurrency when dealing with dataset?
38. How do you merge two datasets into the third dataset in a simple manner?
39. If you are executing these statements in commandObject.Select * from Table1; Select * from Table2? How you will deal result set?
40. How do you sort a dataset.
DataSet dt=new DataSet("mydata");
mydata.Fill(dt,"mydata");
DataView myDataView = dt.Tables["mydata"].DefaultView ;
myDataView.Sort = "id DESC";
DataGrid1.DataSource=myDataView;
DataGrid1.DataBind();
Thanks & Regards
Santosh
Excellent pieces. Keep posting such kind of information on your blog. I really impressed by your blog.
ReplyDeleteHI,
ReplyDeleteI like it So much