Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

251.

When Do We Generally Use Destructors To Release Resources?

Answer»

If the application USES unmanaged RESOURCES such as windows, files, and network CONNECTIONS, we use
destructors to RELEASE resources.

If the application uses unmanaged resources such as windows, files, and network connections, we use
destructors to release resources.

252.

Usually In .net, The Clr Takes Care Of Memory Management. Is There Any Need For A Programmer To Explicitly Release Memory And Resources? If Yes, Why And How?

Answer»

If the application is using expensive EXTERNAL resource, it is recommend to EXPLICITLY RELEASE the resource before the garbage collector runs and frees the object. We can do this by implementing the Dispose method from the IDisposable interface that PERFORMS the necessary cleanup for the object. This can CONSIDERABLY improve the performance of the application.

If the application is using expensive external resource, it is recommend to explicitly release the resource before the garbage collector runs and frees the object. We can do this by implementing the Dispose method from the IDisposable interface that performs the necessary cleanup for the object. This can considerably improve the performance of the application.

253.

Is It Possible To Force Garbage Collector To Run?

Answer»

Yes, it POSSIBLE to force garbage collector to run by calling the Collect() method, but this is not considered a good practice because this might CREATE a performance over head. USUALLY the programmer has no CONTROL over when the garbage collector RUNS. The garbage collector checks for objects that are no longer being used by the application. If it considers an object eligible for destruction, it calls the destructor(if there is one) and reclaims the memory used to store the object.

Yes, it possible to force garbage collector to run by calling the Collect() method, but this is not considered a good practice because this might create a performance over head. Usually the programmer has no control over when the garbage collector runs. The garbage collector checks for objects that are no longer being used by the application. If it considers an object eligible for destruction, it calls the destructor(if there is one) and reclaims the memory used to store the object.

254.

Why Is It Not A Good Idea To Use Empty Destructors?

Answer»

When a CLASS contains a DESTRUCTOR, an entry is created in the FINALIZE queue. When the destructor is called, the garbage collector is INVOKED to process the queue. If the destructor is empty, this just causes a needless loss of performance.

When a class contains a destructor, an entry is created in the Finalize queue. When the destructor is called, the garbage collector is invoked to process the queue. If the destructor is empty, this just causes a needless loss of performance.

255.

Can You Explicitly Call A Destructor?

Answer»

No, you cannot explicitly call a DESTRUCTOR. Destructors are INVOKED automatically by the GARBAGE COLLECTOR.

No, you cannot explicitly call a destructor. Destructors are invoked automatically by the garbage collector.

256.

Can You Pass Parameters To Destructors?

Answer»

No, you cannot PASS PARAMETERS to DESTRUCTORS. HENCE, you cannot OVERLOAD destructors.

No, you cannot pass parameters to destructors. Hence, you cannot overload destructors.

257.

Can Structs In C# Have Destructors?

Answer»

No, STRUCTS can have CONSTRUCTORS but not DESTRUCTORS, only CLASSES can have destructors.

No, structs can have constructors but not destructors, only classes can have destructors.

258.

Can A Class Have More Than 1 Destructor?

Answer»

No, a CLASS can have only 1 DESTRUCTOR.

No, a class can have only 1 destructor.

259.

What Is A Destructor?

Answer»

A Destructor has the same NAME as the class with a TILDE character and is used to DESTROY an instance of a class.

A Destructor has the same name as the class with a tilde character and is used to destroy an instance of a class.

260.

What Is The Ouput Of The Following Program?

Answer»

using System;
NAMESPACE Nested
{
class ContainerClass
{
public ContainerClass()
{
Console.WriteLine("I am a container class");
}
public class InnerClass : ContainerClass
{
public InnerClass()
{
Console.WriteLine("I am an inner class");
}
}
}
class DemoClass : ContainerClass.InnerClass
{
public DemoClass()
{
Console.WriteLine("I am a Demo class");
}
public static void Main()
{
DemoClass DC = new DemoClass();
}
}
}
Output:
I am a container class
I am an inner class
I am a Demo class

The above program has used the concepts of inheritance and nested classes. The ContainerClass is at the top in the inheritance chain. The nested InnerClass DERIVES from outer ContainerClass. FINALLY the DemoClass derives from nested InnerClass. As all the 3 classes are RELATED by inheritance we have the above output.

using System;
namespace Nested
{
class ContainerClass
{
public ContainerClass()
{
Console.WriteLine("I am a container class");
}
public class InnerClass : ContainerClass
{
public InnerClass()
{
Console.WriteLine("I am an inner class");
}
}
}
class DemoClass : ContainerClass.InnerClass
{
public DemoClass()
{
Console.WriteLine("I am a Demo class");
}
public static void Main()
{
DemoClass DC = new DemoClass();
}
}
}
Output:
I am a container class
I am an inner class
I am a Demo class

The above program has used the concepts of inheritance and nested classes. The ContainerClass is at the top in the inheritance chain. The nested InnerClass derives from outer ContainerClass. Finally the DemoClass derives from nested InnerClass. As all the 3 classes are related by inheritance we have the above output.

261.

Can The Nested Class Access, The Containing Class. Give An Example?

Answer»

Yes, the nested class, or inner class can ACCESS the containing or outer class as shown in the example below. Nested types can access private and protected members of the containing type, including any INHERITED private or protected members.

USING SYSTEM;
namespace Nested
{
class ContainerClass
{
string OuterClassVariable = "I am an outer class variable";
public class InnerClass
{
ContainerClass ContainerClassObject = NEW ContainerClass();
string InnerClassVariable = "I am an Inner class variable";
public InnerClass()
{
Console.WriteLine(ContainerClassObject.OuterClassVariable);
Console.WriteLine(this.InnerClassVariable);
}
}
}
class Demo
{
public static void Main()
{
ContainerClass.InnerClass nestedClassObj = new ContainerClass.InnerClass();
}
}
}

Yes, the nested class, or inner class can access the containing or outer class as shown in the example below. Nested types can access private and protected members of the containing type, including any inherited private or protected members.

using System;
namespace Nested
{
class ContainerClass
{
string OuterClassVariable = "I am an outer class variable";
public class InnerClass
{
ContainerClass ContainerClassObject = new ContainerClass();
string InnerClassVariable = "I am an Inner class variable";
public InnerClass()
{
Console.WriteLine(ContainerClassObject.OuterClassVariable);
Console.WriteLine(this.InnerClassVariable);
}
}
}
class Demo
{
public static void Main()
{
ContainerClass.InnerClass nestedClassObj = new ContainerClass.InnerClass();
}
}
}

262.

What Is A Nested Type. Give An Example?

Answer»

A type(class or a struct) defined INSIDE another class or struct is CALLED a NESTED type. An example is shown below. InnerClass is inside ContainerClass, Hence InnerClass is called as nested class.

USING System;
namespace Nested
{
class ContainerClass
{
class InnerClass
{
public string str = "A string variable in nested class";
}
public static void Main()
{
InnerClass nestedClassObj = NEW InnerClass();
Console.WriteLine(nestedClassObj.str);
}
}
}

A type(class or a struct) defined inside another class or struct is called a nested type. An example is shown below. InnerClass is inside ContainerClass, Hence InnerClass is called as nested class.

using System;
namespace Nested
{
class ContainerClass
{
class InnerClass
{
public string str = "A string variable in nested class";
}
public static void Main()
{
InnerClass nestedClassObj = new InnerClass();
Console.WriteLine(nestedClassObj.str);
}
}
}

263.

What Is The Use Of Partial Methods?

Answer»

Partial METHODS can be used to customize generated CODE. They allow for a method name and signature to be reserved, so that generated code can call the method but the developer can decide whether to IMPLEMENT the method. Much like partial classes, partial methods ENABLE code created by a code generator and code created by a human developer to work together WITHOUT run-time costs.

Partial methods can be used to customize generated code. They allow for a method name and signature to be reserved, so that generated code can call the method but the developer can decide whether to implement the method. Much like partial classes, partial methods enable code created by a code generator and code created by a human developer to work together without run-time costs.

264.

How Do You Create Partial Methods?

Answer»

To create a partial method we create the declaration of the method in one part of the partial class and implementation in the other part of the partial class. The implementation is optional. If the implementation is not provided, then the method and all the calls to the method are REMOVED at compile time. Therefore, any code in the partial class can freely use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented. In summary a partial method declaration CONSISTS of two parts. The definition, and the implementation. These may be in separate parts of a partial class, or in the same part. If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.

The FOLLOWING are the points to keep in MIND when creating partial methods.
1. Partial method declarations must begin partial keyword.
2. The return type of a partial method must be VOID.
3. Partial methods can have ref but not out parameters.
4. Partial methods are implicitly private, and therefore they cannot be virtual.
5. Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.

To create a partial method we create the declaration of the method in one part of the partial class and implementation in the other part of the partial class. The implementation is optional. If the implementation is not provided, then the method and all the calls to the method are removed at compile time. Therefore, any code in the partial class can freely use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented. In summary a partial method declaration consists of two parts. The definition, and the implementation. These may be in separate parts of a partial class, or in the same part. If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.

The following are the points to keep in mind when creating partial methods.
1. Partial method declarations must begin partial keyword.
2. The return type of a partial method must be void.
3. Partial methods can have ref but not out parameters.
4. Partial methods are implicitly private, and therefore they cannot be virtual.
5. Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.

265.

Can You Specify Nested Classes As Partial Classes?

Answer»

YES, nested CLASSES can be specified as PARTIAL classes even if the containing class is not partial. An example is SHOWN below.

class ContainerClass
{
PUBLIC partial class Nested
{
void Test1() { }
}
public partial class Nested
{
void Test2() { }
}
}

Yes, nested classes can be specified as partial classes even if the containing class is not partial. An example is shown below.

class ContainerClass
{
public partial class Nested
{
void Test1() { }
}
public partial class Nested
{
void Test2() { }
}
}

266.

Can Different Parts Of A Partial Class Inherit From Different Interfaces?

Answer»

YES, different PARTS of a partial class can INHERIT from different INTERFACES.

Yes, different parts of a partial class can inherit from different interfaces.

267.

Can You Create Partial Delegates And Enumerations?

Answer»

No, you cannot CREATE PARTIAL DELEGATES and ENUMERATIONS.

No, you cannot create partial delegates and enumerations.

268.

Will The Following Code Compile?

Answer»

USING SYSTEM;
namespace PartialClass
{
public partial class Student
{
public void Study()
{
Console.WriteLine("I am studying");
}
}
public abstract partial class Student
{
public void PLAY()
{
Console.WriteLine("I am Playing");
}
}
public class Demo
{
public static void Main()
{
Student StudentObject = new Student();
} }}

No, a compile time error will be GENERATED stating "Cannot create an instance of the abstract class or interface "PartialClass.Student". This is because, if any part is declared abstract, then the whole class becomes abstract. Similarly if any part is declared sealed, then the whole class becomes sealed and if any part declares a BASE class, then the whole class inherits that base class.

using System;
namespace PartialClass
{
public partial class Student
{
public void Study()
{
Console.WriteLine("I am studying");
}
}
public abstract partial class Student
{
public void Play()
{
Console.WriteLine("I am Playing");
}
}
public class Demo
{
public static void Main()
{
Student StudentObject = new Student();
} }}

No, a compile time error will be generated stating "Cannot create an instance of the abstract class or interface "PartialClass.Student". This is because, if any part is declared abstract, then the whole class becomes abstract. Similarly if any part is declared sealed, then the whole class becomes sealed and if any part declares a base class, then the whole class inherits that base class.

269.

Is It Possible To Create Partial Structs, Interfaces And Methods?

Answer»

Yes, it is possible to CREATE partial STRUCTS, interfaces and methods. We can create partial structs, interfaces and methods the same way as we create partial CLASSES.

Yes, it is possible to create partial structs, interfaces and methods. We can create partial structs, interfaces and methods the same way as we create partial classes.

270.

What Are The Advantages Of Using Partial Classes?

Answer»

1. When working on large projects, spreading a class over separate files enables multiple programmers to WORK on it at the same time.

2. When working with automatically GENERATED source, code can be added to the class without having to recreate the source file. Visual Studio uses this APPROACH when it creates Windows Forms, Web SERVICE wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio.

1. When working on large projects, spreading a class over separate files enables multiple programmers to work on it at the same time.

2. When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when it creates Windows Forms, Web service wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio.

271.

What Is A Partial Class. Give An Example?

Answer»

A partial class is a class whose definition is present in 2 or more files. Each source file contains a section of the class, and all PARTS are combined when the application is compiled. To SPLIT a class definition, use the partial keyword as shown in the example below. Student class is split into 2 parts. The first part defines the study() method and the second part defines the Play() method. When we compile this program both the parts will be combined and compiled. NOTE that both the parts uses partial keyword and public access modifier.

using System;
namespace PartialClass
{
public partial class Student
{
public void Study()
{
Console.WriteLine("I am studying");
}
}
public partial class Student
{
public void Play()
{
Console.WriteLine("I am Playing");
}
}
public class Demo
{
public static void Main()
{
Student StudentObject = new Student();
StudentObject.Study();
StudentObject.Play();
} }}

It is very important to keep the following points in MIND when creating partial classes.
1. All the parts must use the partial keyword.
2. All the parts must be available at compile time to form the final class.
3. All the parts must have the same access modifiers - public, private, protected etc.
4. Any class MEMBERS declared in a partial definition are available to all the other parts.
5. The final class is the combination of all the parts at compile time.

A partial class is a class whose definition is present in 2 or more files. Each source file contains a section of the class, and all parts are combined when the application is compiled. To split a class definition, use the partial keyword as shown in the example below. Student class is split into 2 parts. The first part defines the study() method and the second part defines the Play() method. When we compile this program both the parts will be combined and compiled. Note that both the parts uses partial keyword and public access modifier.

using System;
namespace PartialClass
{
public partial class Student
{
public void Study()
{
Console.WriteLine("I am studying");
}
}
public partial class Student
{
public void Play()
{
Console.WriteLine("I am Playing");
}
}
public class Demo
{
public static void Main()
{
Student StudentObject = new Student();
StudentObject.Study();
StudentObject.Play();
} }}

It is very important to keep the following points in mind when creating partial classes.
1. All the parts must use the partial keyword.
2. All the parts must be available at compile time to form the final class.
3. All the parts must have the same access modifiers - public, private, protected etc.
4. Any class members declared in a partial definition are available to all the other parts.
5. The final class is the combination of all the parts at compile time.

272.

What Do You Mean By "explicitly Implemeting An Interface". Give An Example?

Answer»

If a class is IMPLEMENTING the inherited interface member by prefixing the name of the interface, then the class is "Explicitly Implemeting an Interface member". The disadvantage of Explicitly Implemeting an Interface member is that, the class object has to be type casted to the interface type to invoke the interface member. An EXAMPLE is SHOWN below.

using System;
namespace Interfaces
{
interface Car
{
VOID Drive();
}
class Demo : Car
{
// Explicit implementation of an interface member
void Car.Drive()
{
Console.WriteLine("Drive Car");
}
static void Main()
{
Demo DemoObject = new Demo();
//DemoObject.Drive();
// Error: Cannot call explicitly implemented interface method
// using the class object.
// Type CAST the demo object to interface type Car
((Car)DemoObject).Drive();
}
}
}

If a class is implementing the inherited interface member by prefixing the name of the interface, then the class is "Explicitly Implemeting an Interface member". The disadvantage of Explicitly Implemeting an Interface member is that, the class object has to be type casted to the interface type to invoke the interface member. An example is shown below.

using System;
namespace Interfaces
{
interface Car
{
void Drive();
}
class Demo : Car
{
// Explicit implementation of an interface member
void Car.Drive()
{
Console.WriteLine("Drive Car");
}
static void Main()
{
Demo DemoObject = new Demo();
//DemoObject.Drive();
// Error: Cannot call explicitly implemented interface method
// using the class object.
// Type cast the demo object to interface type Car
((Car)DemoObject).Drive();
}
}
}

273.

A Class Inherits From 2 Interfaces And Both The Interfaces Have The Same Method Name As Shown Below. How Should The Class Implement The Drive Method For Both Car And Bus Interface?

Answer»

namespace Interfaces
{
interface Car
{
void Drive();
}
interface Bus
{
void Drive();
}
class Demo : Car,Bus
{
//How to implement the Drive() Method inherited from Bus and Car
}
}

To implement the Drive() method use the fully qualified name as shown in the EXAMPLE below. To CALL the respective interface drive method TYPE CAST the demo object to the respective interface and then call the drive method.

USING System;
namespace Interfaces
{
interface Car
{
void Drive();
}
interface Bus
{
void Drive();
}
class Demo : Car,Bus
{
void Car.Drive()
{
Console.WriteLine("Drive Car");
}
void Bus.Drive()
{
Console.WriteLine("Drive Bus");
}
static void Main()
{
Demo DemoObject = new Demo();
((Car)DemoObject).Drive();
((Bus)DemoObject).Drive();
}
}
}

namespace Interfaces
{
interface Car
{
void Drive();
}
interface Bus
{
void Drive();
}
class Demo : Car,Bus
{
//How to implement the Drive() Method inherited from Bus and Car
}
}

To implement the Drive() method use the fully qualified name as shown in the example below. To call the respective interface drive method type cast the demo object to the respective interface and then call the drive method.

using System;
namespace Interfaces
{
interface Car
{
void Drive();
}
interface Bus
{
void Drive();
}
class Demo : Car,Bus
{
void Car.Drive()
{
Console.WriteLine("Drive Car");
}
void Bus.Drive()
{
Console.WriteLine("Drive Bus");
}
static void Main()
{
Demo DemoObject = new Demo();
((Car)DemoObject).Drive();
((Bus)DemoObject).Drive();
}
}
}

274.

If A Class Inherits An Interface, What Are The 2 Options Available For That Class?

Answer»

Option 1: Provide IMPLEMENTATION for all the members inheirted from the INTERFACE.

namespace INTERFACES
{
interface Interface1
{
VOID Interface1Method();
}
class BaseClass1 : Interface1
{
public void Interface1Method()
{
Console.WriteLine("Interface1 Method");
}
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
}

Option 2: If the class does not wish to provide Implementation for all the members inheirted from the interface, then the class has to be marked as abstract.

namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}
abstract class BaseClass1 : Interface1
{
abstract public void Interface1Method();
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
}

Option 1: Provide Implementation for all the members inheirted from the interface.

namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}
class BaseClass1 : Interface1
{
public void Interface1Method()
{
Console.WriteLine("Interface1 Method");
}
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
}

Option 2: If the class does not wish to provide Implementation for all the members inheirted from the interface, then the class has to be marked as abstract.

namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}
abstract class BaseClass1 : Interface1
{
abstract public void Interface1Method();
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
}

275.

Can You Create An Instance Of An Interface?

Answer»

No, you cannot CREATE an INSTANCE of an INTERFACE.

No, you cannot create an instance of an interface.

276.

Can An Interface Inherit From Another Interface?

Answer»

Yes, an interface can inherit from ANOTHER interface. It is POSSIBLE for a class to inherit an interface multiple times, through BASE classes or interfaces it inherits. In this case, the class can only implement the interface one time, if it is declared as part of the new class. If the inherited interface is not declared as part of the new class, its IMPLEMENTATION is provided by the base class that declared it. It is possible for a base class to implement interface members using virtual members; in that case, the class INHERITING the interface can change the interface behavior by overriding the virtual members.

Yes, an interface can inherit from another interface. It is possible for a class to inherit an interface multiple times, through base classes or interfaces it inherits. In this case, the class can only implement the interface one time, if it is declared as part of the new class. If the inherited interface is not declared as part of the new class, its implementation is provided by the base class that declared it. It is possible for a base class to implement interface members using virtual members; in that case, the class inheriting the interface can change the interface behavior by overriding the virtual members.

277.

What Is The Difference Between Class Inheritance And Interface Inheritance?

Answer»

Classes and STRUCTS can INHERIT from interfaces just like how classes can inherit a base class or STRUCT. However there are 2 differences.
1. A class or a struct can inherit from more than one interface at the same time where as A class or a struct cannot inherit from more than one class at the same time. An example DEPICTING the same is shown below.

using System;
NAMESPACE Interfaces
{
interface Interface1
{
void Interface1Method();
}
interface Interface2
{
void Interface2Method();
}
class BaseClass1
{
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
class BaseClass2
{
public void BaseClass2Method()
{
Console.WriteLine("BaseClass2 Method");
}
}
//Error : A class cannot inherit from more than one class at the same time
//class DerivedClass : BaseClass1, BaseClass2
//{
//}
//A class can inherit from more than one interface at the same time
public class Demo : Interface1, Interface2
{
public void Interface1Method()
{
Console.WriteLine("Interface1 Method");
}
public void Interface2Method()
{
Console.WriteLine("Interface2 Method");
}
public static void Main()
{
Demo DemoObject = new Demo();
DemoObject.Interface1Method();
DemoObject.Interface2Method();
}
}
}

2. When a class or struct inherits an interface, it inherits only the method names and signatures, because the interface itself contains no implementations.

Classes and structs can inherit from interfaces just like how classes can inherit a base class or struct. However there are 2 differences.
1. A class or a struct can inherit from more than one interface at the same time where as A class or a struct cannot inherit from more than one class at the same time. An example depicting the same is shown below.

using System;
namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}
interface Interface2
{
void Interface2Method();
}
class BaseClass1
{
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
class BaseClass2
{
public void BaseClass2Method()
{
Console.WriteLine("BaseClass2 Method");
}
}
//Error : A class cannot inherit from more than one class at the same time
//class DerivedClass : BaseClass1, BaseClass2
//{
//}
//A class can inherit from more than one interface at the same time
public class Demo : Interface1, Interface2
{
public void Interface1Method()
{
Console.WriteLine("Interface1 Method");
}
public void Interface2Method()
{
Console.WriteLine("Interface2 Method");
}
public static void Main()
{
Demo DemoObject = new Demo();
DemoObject.Interface1Method();
DemoObject.Interface2Method();
}
}
}

2. When a class or struct inherits an interface, it inherits only the method names and signatures, because the interface itself contains no implementations.

278.

Can An Interface Contain Fields?

Answer»

No, an INTERFACE cannot CONTAIN FIELDS.

No, an Interface cannot contain fields.

279.

Explain What Is An Interface In C#?

Answer»

An Interface in C# is created using the interface keyword. An example is shown below.

using System;
namespace Interfaces
{
interface IBankCustomer
{
VOID DepositMoney();
void WithdrawMoney();
}
public class Demo : IBankCustomer
{
public void DepositMoney()
{
Console.WriteLine("Deposit Money");
}
public void WithdrawMoney()
{
Console.WriteLine("Withdraw Money");
}
public static void Main()
{
Demo DemoObject = new Demo();
DemoObject.DepositMoney();
DemoObject.WithdrawMoney();
}
}
}

In our example we created IBankCustomer interface. The interface declares 2 methods.
1. void DepositMoney();
2. void WithdrawMoney();

Notice that method declarations does not have access modifiers like public, private, etc. By default all interface members are public. It is a compile time error to use access modifiers on interface MEMBER declarations. Also notice that the interface methods have only declarations and not implementation. It is a compile time error to provide implementation for any interface member. In our example as the Demo class is inherited from the IBankCustomer interface, the Demo class has to provide the implementation for both the methods (WithdrawMoney() and DepositMoney()) that is inherited from the interface. If the class fails to provide implementation for any of the inherited interface member, a compile time error will be generated. Interfaces can consist of methods, properties, events, indexers, or any combination of those four member types. When a class or a struct INHERITS an interface, the class or struct must provide implementation for all of the members declared in the interface. The interface itself PROVIDES no FUNCTIONALITY that a class or struct can inherit in the way that base class functionality can be inherited. However, if a base class implements an interface, the derived class inherits that implementation.

An Interface in C# is created using the interface keyword. An example is shown below.

using System;
namespace Interfaces
{
interface IBankCustomer
{
void DepositMoney();
void WithdrawMoney();
}
public class Demo : IBankCustomer
{
public void DepositMoney()
{
Console.WriteLine("Deposit Money");
}
public void WithdrawMoney()
{
Console.WriteLine("Withdraw Money");
}
public static void Main()
{
Demo DemoObject = new Demo();
DemoObject.DepositMoney();
DemoObject.WithdrawMoney();
}
}
}

In our example we created IBankCustomer interface. The interface declares 2 methods.
1. void DepositMoney();
2. void WithdrawMoney();

Notice that method declarations does not have access modifiers like public, private, etc. By default all interface members are public. It is a compile time error to use access modifiers on interface member declarations. Also notice that the interface methods have only declarations and not implementation. It is a compile time error to provide implementation for any interface member. In our example as the Demo class is inherited from the IBankCustomer interface, the Demo class has to provide the implementation for both the methods (WithdrawMoney() and DepositMoney()) that is inherited from the interface. If the class fails to provide implementation for any of the inherited interface member, a compile time error will be generated. Interfaces can consist of methods, properties, events, indexers, or any combination of those four member types. When a class or a struct inherits an interface, the class or struct must provide implementation for all of the members declared in the interface. The interface itself provides no functionality that a class or struct can inherit in the way that base class functionality can be inherited. However, if a base class implements an interface, the derived class inherits that implementation.

280.

Are C# Generics The Same As C++ Templates?

Answer»

No, not REALLY. There are some SIMILARITIES, but there are ALSO FUNDAMENTAL DIFFERENCES.

No, not really. There are some similarities, but there are also fundamental differences.

281.

What Are The New Features In C# 2.0?

Answer»

Support for all of the new framework features such as generics, anonymous methods, PARTIAL classes, iterators and static classes.

Delegate inference is a new feature of the C# compiler which makes delegate usage a little simpler. It allows you to write this:
Thread t = new Thread(ThreadFunc);
instead of this:
Thread t = new Thread( new ThreadStart(ThreadFunc) );

Another minor but WELCOME addition is the explicit global namespace, which fixes a HOLE in namespace usage in C# 1.x. You can prefix a type NAME with global:: to indicate that the type BELONGS to the global namespace, thus avoiding problems where the compiler infers the namespace and gets it wrong.

Finally C# 2.0 includes some syntactic sugar for the new System.Nullable type. You can use T? as a synonym for System.Nullable<T>, where T is a value type. As suggested by the name, this allows values of the type to be 'null', or 'undefined'.

Support for all of the new framework features such as generics, anonymous methods, partial classes, iterators and static classes.

Delegate inference is a new feature of the C# compiler which makes delegate usage a little simpler. It allows you to write this:
Thread t = new Thread(ThreadFunc);
instead of this:
Thread t = new Thread( new ThreadStart(ThreadFunc) );

Another minor but welcome addition is the explicit global namespace, which fixes a hole in namespace usage in C# 1.x. You can prefix a type name with global:: to indicate that the type belongs to the global namespace, thus avoiding problems where the compiler infers the namespace and gets it wrong.

Finally C# 2.0 includes some syntactic sugar for the new System.Nullable type. You can use T? as a synonym for System.Nullable<T>, where T is a value type. As suggested by the name, this allows values of the type to be 'null', or 'undefined'.

282.

How Do I Enforce Const Correctness In C#?

Answer»

You can't - at least not in the same way you do in C++. C# (actually, the CLI) has no real concept of const correctness, For EXAMPLE, there's no way to specify that a method should not modify an argument passed in to it. And there's no way to specify that a method does not modify the object on which it is acting.

To GET a feel for the angst this causes among some C++ programmers, READ the feedback on this post from RAYMOND Chen.

There are of course ways of addressing this issue. For example, see Brad Abram's post (and associated feedback) for some IDEAS on adding optional read-only behaviour to collection classes.

You can't - at least not in the same way you do in C++. C# (actually, the CLI) has no real concept of const correctness, For example, there's no way to specify that a method should not modify an argument passed in to it. And there's no way to specify that a method does not modify the object on which it is acting.

To get a feel for the angst this causes among some C++ programmers, read the feedback on this post from Raymond Chen.

There are of course ways of addressing this issue. For example, see Brad Abram's post (and associated feedback) for some ideas on adding optional read-only behaviour to collection classes.

283.

What Is The Difference Between == And Object.equals?

Answer»

For value types, == and Equals() usually compare two objects by value. For example:
int x = 10;
int y = 10;
Console.WriteLine( x == y );
Console.WriteLine( x.Equals(y) );
will display:
True
True

However things are more complex for reference types. Generally speaking, for reference types == is expected to perform an identity comparison, i.e. it will only return true if both references point to the same object. By contrast, Equals() is expected to perform a value comparison, i.e. it will return true if the references point to objects that are EQUIVALENT. For example:
StringBuilder s1 = new StringBuilder("fred");
StringBuilder s2 = new StringBuilder("fred");
Console.WriteLine( s1 == s2 );
Console.WriteLine( s1.Equals(s2) );
will display:
False
True

s1 and s2 are different objects (hence == returns false), but they are equivalent (hence Equals() returns true).

Unfortunately there are exceptions to these rules. The IMPLEMENTATION of Equals() in System.Object (the one you'll inherit by default if you write a class) compares identity, i.e. it's the same as operator==. So Equals() only tests for EQUIVALENCE if the class author overrides the METHOD (and implements it correctly). Another exception is the string class - its operator== compares value rather than identity.

Bottom line: If you want to perform an identity comparison use the ReferenceEquals() method. If you want to perform a value comparison, use Equals() but be aware that it will only work if the type has overridden the default implementation. Avoid operator== with reference types (except perhaps strings), as it's SIMPLY too ambiguous.

For value types, == and Equals() usually compare two objects by value. For example:
int x = 10;
int y = 10;
Console.WriteLine( x == y );
Console.WriteLine( x.Equals(y) );
will display:
True
True

However things are more complex for reference types. Generally speaking, for reference types == is expected to perform an identity comparison, i.e. it will only return true if both references point to the same object. By contrast, Equals() is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent. For example:
StringBuilder s1 = new StringBuilder("fred");
StringBuilder s2 = new StringBuilder("fred");
Console.WriteLine( s1 == s2 );
Console.WriteLine( s1.Equals(s2) );
will display:
False
True

s1 and s2 are different objects (hence == returns false), but they are equivalent (hence Equals() returns true).

Unfortunately there are exceptions to these rules. The implementation of Equals() in System.Object (the one you'll inherit by default if you write a class) compares identity, i.e. it's the same as operator==. So Equals() only tests for equivalence if the class author overrides the method (and implements it correctly). Another exception is the string class - its operator== compares value rather than identity.

Bottom line: If you want to perform an identity comparison use the ReferenceEquals() method. If you want to perform a value comparison, use Equals() but be aware that it will only work if the type has overridden the default implementation. Avoid operator== with reference types (except perhaps strings), as it's simply too ambiguous.

284.

How Do I Use The 'using' Keyword With Multiple Objects?

Answer»

You can NEST USING statements, like this:
using( OBJ1 )
{
using( obj2 )
{
...
}
}

However consider using this more AESTHETICALLY PLEASING (but functionally identical) formatting:
using( obj1 )
using( obj2 )
{
...
}

You can nest using statements, like this:
using( obj1 )
{
using( obj2 )
{
...
}
}

However consider using this more aesthetically pleasing (but functionally identical) formatting:
using( obj1 )
using( obj2 )
{
...
}

285.

How Can I Make Sure My C# Classes Will Interoperate With Other .net Languages?

Answer»

MAKE sure your C# code conforms to the Common Language Subset (CLS). To help with this, add the [assembly:CLSCompliant(true)] global ATTRIBUTE to your C# source files. The COMPILER will EMIT an error if you use a C# FEATURE which is not CLS-compliant.

Make sure your C# code conforms to the Common Language Subset (CLS). To help with this, add the [assembly:CLSCompliant(true)] global attribute to your C# source files. The compiler will emit an error if you use a C# feature which is not CLS-compliant.

286.

Does C# Do Array Bounds Checking?

Answer»

YES. An IndexOutOfRange EXCEPTION is USED to SIGNAL an ERROR.

Yes. An IndexOutOfRange exception is used to signal an error.

287.

How Can I Process Command-line Arguments?

Answer»

Like this:
USING System;
class CApp
{
PUBLIC STATIC VOID Main( string[] args )
{
Console.WriteLine( "You passed the following arguments:" );
FOREACH( string arg in args )
Console.WriteLine( arg );
}
}

Like this:
using System;
class CApp
{
public static void Main( string[] args )
{
Console.WriteLine( "You passed the following arguments:" );
foreach( string arg in args )
Console.WriteLine( arg );
}
}

288.

Does C# Support A Variable Number Of Arguments?

Answer»

Yes, using the PARAMS keyword. The arguments are specified as a list of arguments of a SPECIFIC TYPE, e.g. INT. For ultimate flexibility, the type can be object. The standard example of a method which USES this approach is System.Console.WriteLine().

Yes, using the params keyword. The arguments are specified as a list of arguments of a specific type, e.g. int. For ultimate flexibility, the type can be object. The standard example of a method which uses this approach is System.Console.WriteLine().

289.

How Do I Do A Case-insensitive String Comparison?

Answer»

USE the String.Compare function. Its third parameter is a boolean which SPECIFIES WHETHER case should be ignored or not.

"fred" == "Fred" // false
System.String.Compare( "fred", "Fred", TRUE ) // true

Use the String.Compare function. Its third parameter is a boolean which specifies whether case should be ignored or not.

"fred" == "Fred" // false
System.String.Compare( "fred", "Fred", true ) // true

290.

Can I Get The Name Of A Type At Runtime?

Answer»

Yes, USE the GetType method of the OBJECT class (which all types inherit from). For example:
using System;
class CTest
{
class CApp
{
public static void Main()
{
long i = 10;
CTest ctest = new CTest();
DisplayTypeInfo( ctest );
DisplayTypeInfo( i );
}
static void DisplayTypeInfo( object OBJ )
{
Console.WriteLine( "Type name = {0}, full type name = {1}", obj.GetType(), obj.GetType().FullName );
}
}
}
PRODUCES the following OUTPUT:
Type name = CTest, full type name = CTest
Type name = Int64, full type name = System.Int64

Yes, use the GetType method of the object class (which all types inherit from). For example:
using System;
class CTest
{
class CApp
{
public static void Main()
{
long i = 10;
CTest ctest = new CTest();
DisplayTypeInfo( ctest );
DisplayTypeInfo( i );
}
static void DisplayTypeInfo( object obj )
{
Console.WriteLine( "Type name = {0}, full type name = {1}", obj.GetType(), obj.GetType().FullName );
}
}
}
produces the following output:
Type name = CTest, full type name = CTest
Type name = Int64, full type name = System.Int64

291.

How Can I Check The Type Of An Object At Runtime?

Answer»

You can use the is keyword. For example:
using SYSTEM;
class CApp
{
public static void Main()
{
string s = "fred";
long i = 10;
Console.WriteLine( "{0} is {1}an integer", s, (IsInteger(s) ? "" : "not ") );
Console.WriteLine( "{0} is {1}an integer", i, (IsInteger(i) ? "" : "not ") );
}
static bool IsInteger( object OBJ )
{
if( obj is int || obj is long )
return true;
else
return FALSE;
}
}
PRODUCES the output:
fred is not an integer
10 is an integer

You can use the is keyword. For example:
using System;
class CApp
{
public static void Main()
{
string s = "fred";
long i = 10;
Console.WriteLine( "{0} is {1}an integer", s, (IsInteger(s) ? "" : "not ") );
Console.WriteLine( "{0} is {1}an integer", i, (IsInteger(i) ? "" : "not ") );
}
static bool IsInteger( object obj )
{
if( obj is int || obj is long )
return true;
else
return false;
}
}
produces the output:
fred is not an integer
10 is an integer

292.

Does C# Have A 'throws' Clause?

Answer»

No, UNLIKE Java, C# does not require (or even allow) the DEVELOPER to specify the EXCEPTIONS that a method can THROW.

No, unlike Java, C# does not require (or even allow) the developer to specify the exceptions that a method can throw.

293.

When Should I Throw An Exception?

Answer»

This is the SUBJECT of some debate, and is partly a matter of taste. However, it is accepted by many that exceptions should be thrown only when an 'UNEXPECTED' error OCCURS. How do you decide if an error is expected or unexpected? This is a JUDGEMENT call, but a straightforward example of an expected error is failing to read from a file because the seek pointer is at the end of the file, whereas an example of an unexpected error is failing to allocate memory from the heap.

This is the subject of some debate, and is partly a matter of taste. However, it is accepted by many that exceptions should be thrown only when an 'unexpected' error occurs. How do you decide if an error is expected or unexpected? This is a judgement call, but a straightforward example of an expected error is failing to read from a file because the seek pointer is at the end of the file, whereas an example of an unexpected error is failing to allocate memory from the heap.

294.

Does The System.exception Class Have Any Cool Features?

Answer»

Yes - the feature which stands out is the StackTrace property. This provides a call stack which records where the exception was thrown from. For example, the following code:
USING System;
class CApp
{
PUBLIC static void Main()
{
try
{
f();
}
CATCH( Exception e )
{
Console.WriteLine( "System.Exception stack trace = \n{0}", e.StackTrace );
}
}
static void f()
{
throw new Exception( "f WENT pear-shaped" );
}
}
produces this output:
System.Exception stack trace =
at CApp.f()
at CApp.Main()

Note, however, that this stack trace was produced from a debug build. A release build may OPTIMISE away some of the method calls which could mean that the call stack isn't quite what you expect.

Yes - the feature which stands out is the StackTrace property. This provides a call stack which records where the exception was thrown from. For example, the following code:
using System;
class CApp
{
public static void Main()
{
try
{
f();
}
catch( Exception e )
{
Console.WriteLine( "System.Exception stack trace = \n{0}", e.StackTrace );
}
}
static void f()
{
throw new Exception( "f went pear-shaped" );
}
}
produces this output:
System.Exception stack trace =
at CApp.f()
at CApp.Main()

Note, however, that this stack trace was produced from a debug build. A release build may optimise away some of the method calls which could mean that the call stack isn't quite what you expect.

295.

Can I Define My Own Exceptions?

Answer»

YES, just DERIVE your EXCEPTION CLASS from System.Exception.

Yes, just derive your exception class from System.Exception.

296.

What Types Of Object Can I Throw As Exceptions?

Answer»

Only INSTANCES of the System.Exception CLASSES, or classes DERIVED from System.Exception. This is in sharp CONTRAST with C++ where instances of almost any type can be THROWN.

Only instances of the System.Exception classes, or classes derived from System.Exception. This is in sharp contrast with C++ where instances of almost any type can be thrown.

297.

Can I Use Exceptions In C#?

Answer»

Yes, in fact exceptions are the recommended error-handling mechanism in C# (and in .NET in GENERAL). Most of the .NET FRAMEWORK CLASSES use exceptions to SIGNAL errors.

Yes, in fact exceptions are the recommended error-handling mechanism in C# (and in .NET in general). Most of the .NET framework classes use exceptions to signal errors.

298.

Should I Make My Destructor Virtual?

Answer»

A C# destructor is REALLY just an OVERRIDE of the System.Object FINALIZE method, and so is VIRTUAL by definition.

A C# destructor is really just an override of the System.Object Finalize method, and so is virtual by definition.

299.

Can I Call A Virtual Method From A Constructor/destructor?

Answer»

Yes, but it's generally not a good idea. The mechanics of OBJECT construction in .NET are QUITE different from C++, and this affects virtual method calls in constructors.

C++ CONSTRUCTS objects from base to derived, so when the base constructor is executing the object is effectively a base object, and virtual method calls are routed to the base class implementation. By contrast, in .NET the derived constructor is executed first, which means the object is always a derived object and virtual method calls are always routed to the derived implementation. (Note that the C# compiler inserts a CALL to the base class constructor at the start of the derived constructor, thus preserving standard OO semantics by CREATING the illusion that the base constructor is executed first.)

The same issue arises when calling virtual methods from C# destructors. A virtual method call in a base destructor will be routed to the derived implementation.

Yes, but it's generally not a good idea. The mechanics of object construction in .NET are quite different from C++, and this affects virtual method calls in constructors.

C++ constructs objects from base to derived, so when the base constructor is executing the object is effectively a base object, and virtual method calls are routed to the base class implementation. By contrast, in .NET the derived constructor is executed first, which means the object is always a derived object and virtual method calls are always routed to the derived implementation. (Note that the C# compiler inserts a call to the base class constructor at the start of the derived constructor, thus preserving standard OO semantics by creating the illusion that the base constructor is executed first.)

The same issue arises when calling virtual methods from C# destructors. A virtual method call in a base destructor will be routed to the derived implementation.

300.

How Do I Declare A Pure Virtual Function In C#?

Answer»

Use the abstract MODIFIER on the method. The class must also be marked as abstract (naturally). NOTE that abstract methods cannot have an IMPLEMENTATION (unlike pure virtual C++ methods).

Use the abstract modifier on the method. The class must also be marked as abstract (naturally). Note that abstract methods cannot have an implementation (unlike pure virtual C++ methods).