What are the new
features introduced in c# 4.0?
This question is basically asked to check, if you are passionate about catching up with latest technological advancements. The list below shows a few of the new features introduced in c# 4.0. If you are aware of any other new features, please submit those using the from at the end of this post.
1. Optional and Named Parameters
2. COM Interoperability Enhancements
3. Covariance and Contra-variance
4. Dynamic Type Introduction
What's the difference between IEnumerable<T> and List<T> ?
1. IEnumerable is an interface, where as List is one specific implementation of IEnumerable. List is a class.
2. FOR-EACH loop is the only possible way to iterate through a collection of IEnumerable, where as List can be iterated using several ways. List can also be indexed by an int index, element can be added to and removed from and have items inserted at a particular index.
3. IEnumerable doesn't allow random access, where as List does allow random access using integral index.
4. In general from a performance standpoint, iterating thru IEnumerable is much faster than iterating thru a List.
Difference between EXE and DLL?
1. .EXE is an executable file and can run by itself as an application, where as .DLL is usullay consumed by a .EXE or by another .DLL and we cannot run or execute .DLL directly.
2. For example, In .NET, compiling a Console Application or a Windows Application generates .EXE, where as compiling a Class Library Project or an ASP.NET web application generates .DLL. In .NET framework, both .EXE and .DLL are called as assemblies.
What are the difference between interfaces and abstract classes?
1. Abstract classes can have implementations for some of its members, but the interface can't have implementation for any of its members.
2. Interfaces cannot have fields where as an abstract class can have fields.
3. An interface can inherit from another interface only and cannot inherit from an abstract class, where as an abstract class can inherit from another abstract class or another interface.
4. A class can inherit from multiple interfaces at the same time, where as a class cannot inherit from multiple classes at the same time.
5. Abstract class members can have access modifiers where as interface members cannot have access modifiers.
What is a delegate?
A delegate is a type safe function pointer. Using delegates you can pass methods as parameters. To pass a method as a parameter, to a delegate, the signature of the method must match the signature of the delegate. This is why, delegates are called type safe function pointers.
What is the main use of delegates in C#?
Delegates are mainly used to define call back methods.
What do you mean by chaining delegates?
Or
What is a multicast delegate?
The capability of calling multiple methods on a single event is called as chaining delegates. Let me give you an example to understand this further.
1. Create a new asp.net web application
2. Drag and drop a button control and leave the ID as Button1.
3. On the code behind file, add the code shown below.
When you click the Button now, both Method1 and Method2 will be executed. So, this capability of calling multiple methods on a single event is called as chaining delegates. In the example, we are using EventHandler delegate, to hook up Method1 and Method2 to the click event of the button control. Since, the EventHandler delegate is now pointing to multiple methods, it is also called as multicast delegate.
What are the advantages of using interfaces?
Interfaces are very powerful. If properly used, interfaces provide all the advantages as listed below.
1. Interfaces allow us to implement polymorphic behaviour. Ofcourse, abstract classes can also be used to implement polymorphic behaviour.
2. Interfaces allow us to develop very loosely coupled systems.
3. Interfaces enable mocking for better unit testing.
4. Interfaces enables us to implement multiple class inheritance in C#.
5. Interfaces are great for implementing Inverson of Control or Dependancy Injection.
6. Interfaces enable parallel application development.
What are the advantages and disadvantages of using arrays?
Advantages of using arrays:
1. Arrays are strongly typed, meaning you can only have one type of elements in the array. The strongly typed nature of arrays gives us
2 advantages. One, the performance will be much better because boxing and unboxing will not happen. Second, run time errors can be prevented because of type mis matches. Type mis matches and runtime errors are most commonly seen with collection classes like ArrayList, Queue, Stack etc, that are present in System.Collections namespace.
Disadvantages of using arrays:
1. Arrays are fixed in size and cannot grow over time, where ArrayList in System.Collections namespace can grow dynamically.
2. Arrays are zero index based, and hence a little difficult to work with. The only way to store or retrieve elements from arrays, is to use integral index. Arrays donot provide convinient methods like Add(), Remove() etc provided by collection classes found in System.Collections or System.Collections.Generics namespaces, which are very easy to work with.
Explain what is an Interface in C#?
An Interface in C# is created using the interface keyword. An example is shown below.
This question is basically asked to check, if you are passionate about catching up with latest technological advancements. The list below shows a few of the new features introduced in c# 4.0. If you are aware of any other new features, please submit those using the from at the end of this post.
1. Optional and Named Parameters
2. COM Interoperability Enhancements
3. Covariance and Contra-variance
4. Dynamic Type Introduction
What's the difference between IEnumerable<T> and List<T> ?
1. IEnumerable is an interface, where as List is one specific implementation of IEnumerable. List is a class.
2. FOR-EACH loop is the only possible way to iterate through a collection of IEnumerable, where as List can be iterated using several ways. List can also be indexed by an int index, element can be added to and removed from and have items inserted at a particular index.
3. IEnumerable doesn't allow random access, where as List does allow random access using integral index.
4. In general from a performance standpoint, iterating thru IEnumerable is much faster than iterating thru a List.
Difference between EXE and DLL?
1. .EXE is an executable file and can run by itself as an application, where as .DLL is usullay consumed by a .EXE or by another .DLL and we cannot run or execute .DLL directly.
2. For example, In .NET, compiling a Console Application or a Windows Application generates .EXE, where as compiling a Class Library Project or an ASP.NET web application generates .DLL. In .NET framework, both .EXE and .DLL are called as assemblies.
What are the difference between interfaces and abstract classes?
1. Abstract classes can have implementations for some of its members, but the interface can't have implementation for any of its members.
2. Interfaces cannot have fields where as an abstract class can have fields.
3. An interface can inherit from another interface only and cannot inherit from an abstract class, where as an abstract class can inherit from another abstract class or another interface.
4. A class can inherit from multiple interfaces at the same time, where as a class cannot inherit from multiple classes at the same time.
5. Abstract class members can have access modifiers where as interface members cannot have access modifiers.
What is a delegate?
A delegate is a type safe function pointer. Using delegates you can pass methods as parameters. To pass a method as a parameter, to a delegate, the signature of the method must match the signature of the delegate. This is why, delegates are called type safe function pointers.
What is the main use of delegates in C#?
Delegates are mainly used to define call back methods.
What do you mean by chaining delegates?
Or
What is a multicast delegate?
The capability of calling multiple methods on a single event is called as chaining delegates. Let me give you an example to understand this further.
1. Create a new asp.net web application
2. Drag and drop a button control and leave the ID as Button1.
3. On the code behind file, add the code shown below.
When you click the Button now, both Method1 and Method2 will be executed. So, this capability of calling multiple methods on a single event is called as chaining delegates. In the example, we are using EventHandler delegate, to hook up Method1 and Method2 to the click event of the button control. Since, the EventHandler delegate is now pointing to multiple methods, it is also called as multicast delegate.
What are the advantages of using interfaces?
Interfaces are very powerful. If properly used, interfaces provide all the advantages as listed below.
1. Interfaces allow us to implement polymorphic behaviour. Ofcourse, abstract classes can also be used to implement polymorphic behaviour.
2. Interfaces allow us to develop very loosely coupled systems.
3. Interfaces enable mocking for better unit testing.
4. Interfaces enables us to implement multiple class inheritance in C#.
5. Interfaces are great for implementing Inverson of Control or Dependancy Injection.
6. Interfaces enable parallel application development.
What are the advantages and disadvantages of using arrays?
Advantages of using arrays:
1. Arrays are strongly typed, meaning you can only have one type of elements in the array. The strongly typed nature of arrays gives us
2 advantages. One, the performance will be much better because boxing and unboxing will not happen. Second, run time errors can be prevented because of type mis matches. Type mis matches and runtime errors are most commonly seen with collection classes like ArrayList, Queue, Stack etc, that are present in System.Collections namespace.
Disadvantages of using arrays:
1. Arrays are fixed in size and cannot grow over time, where ArrayList in System.Collections namespace can grow dynamically.
2. Arrays are zero index based, and hence a little difficult to work with. The only way to store or retrieve elements from arrays, is to use integral index. Arrays donot provide convinient methods like Add(), Remove() etc provided by collection classes found in System.Collections or System.Collections.Generics namespaces, which are very easy to work with.
Explain what is an Interface in C#?
An Interface in C# is created using the interface keyword. An example is shown below.
Code:
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();
}
}
}
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();
}
}
}
Can an Interface contain fields?
No, an Interface cannot contain fields.
Can an interface inherit from another interface?
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.
Can you create an instance of an interface?
No, you cannot create an instance of an interface.
What is a partial class. Give an example?
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.
Code:
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();
}
}
}
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.
What are the advantages of using partial classes?
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.
Is it possible to create partial structs, interfaces and methods?
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.
Can you create partial delegates and enumerations?
No, you cannot create partial delegates and enumerations.
Can different parts of a partial class inherit from different interfaces?
Yes, different parts of a partial class can inherit from different interfaces.
Can you specify nested classes as partial classes?
Yes, nested classes can be specified as partial classes even if the containing class is not partial. An example is shown below.
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.
What are the advantages of using partial classes?
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.
Is it possible to create partial structs, interfaces and methods?
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.
Can you create partial delegates and enumerations?
No, you cannot create partial delegates and enumerations.
Can different parts of a partial class inherit from different interfaces?
Yes, different parts of a partial class can inherit from different interfaces.
Can you specify nested classes as partial classes?
Yes, nested classes can be specified as partial classes even if the containing class is not partial. An example is shown below.
Code:
class
ContainerClass
{
public partial class Nested
{
void Test1() { }
}
public partial class Nested
{
void Test2() { }
}
}
{
public partial class Nested
{
void Test1() { }
}
public partial class Nested
{
void Test2() { }
}
}
How do you create partial methods?
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.
What is the use of partial methods?
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.
What is a nested type. Give an example?
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.
Code:
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);
}
}
}
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);
}
}
}
What is a Destructor?
A Destructor has the same name as the class with a tilde character and is used to destroy an instance of a class.
Can a class have more than 1 destructor?
No, a class can have only 1 destructor.
Can structs in C# have destructors?
No, structs can have constructors but not destructors, only classes can have destructors.
Can you pass parameters to destructors?
No, you cannot pass parameters to destructors. Hence, you cannot overload destructors.
Can you explicitly call a destructor?
No, you cannot explicitly call a destructor. Destructors are invoked automatically by the garbage collector.
Why is it not a good idea to use Empty destructors?
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.
Is it possible to force garbage collector to run?
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.
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?
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.
When do we generally use destructors to release resources?
If the application uses unmanaged resources such as windows, files, and network connections, we use destructors to release resources.
What is a constructor in C#?
Constructor is a class method that is executed when an object of a class is created. Constructor has the same name as the class, and usually used to initialize the data members of the new object.
In C#, What will happen if you do not explicitly provide a constructor for a class?
If you do not provide a constructor explicitly for your class, C# will create one by default that instantiates the object and sets all the member variables to their default values.
Structs are not reference types. Can structs have constructors?
Yes, even though Structs are not reference types, structs can have constructors.
We cannot create instances of static classes. Can we have constructors for static classes?
Yes, static classes can also have constructors.
Can you prevent a class from being instantiated?
Yes, a class can be prevented from being instantiated by using a private constructor as shown in the example below.
Code:
using System;
namespace TestConsole
{
class Program
{
public static void Main()
{
//Error cannot create instance of a class with private constructor
SampleClass SC = new SampleClass();
}
}
class SampleClass
{
double PI = 3.141;
private SampleClass()
{
}
}
}
namespace TestConsole
{
class Program
{
public static void Main()
{
//Error cannot create instance of a class with private constructor
SampleClass SC = new SampleClass();
}
}
class SampleClass
{
double PI = 3.141;
private SampleClass()
{
}
}
}
Can a class or a struct have multiple constructors?
Yes, a class or a struct can have multiple constructors. Constructors in csharp can be overloaded.
Can a child class call the constructor of a base class?
Yes, a child class can call the constructor of a base class by using the base keyword as shown in the example below.
Code:
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}
class ChildClass : BaseClass
{
public ChildClass(string str): base(str)
{
}
public static void Main()
{
ChildClass CC = new ChildClass("Calling base class constructor from child class");
}
}
}
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}
class ChildClass : BaseClass
{
public ChildClass(string str): base(str)
{
}
public static void Main()
{
ChildClass CC = new ChildClass("Calling base class constructor from child class");
}
}
}
If a child class
instance is created, which class constructor is called first - base class or
child class?
When an instance of a child class is created, the base class constructor is called before the child class constructor. An example is shown below.
When an instance of a child class is created, the base class constructor is called before the child class constructor. An example is shown below.
Code:
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class constructor");
}
}
class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}
namespace TestConsole
{
class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class constructor");
}
}
class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}
Can a class have static constructor?
Yes, a class can have static constructor. Static constructors are called automatically, immediately before any static fields are accessed, and are generally used to initialize static class members. It is called automatically before the first instance is created or any static members are referenced. Static constructors are called before instance constructors. An example is shown below.
Code:
using System;
namespace TestConsole
{
class Program
{
static int I;
static Program()
{
I = 100;
Console.WriteLine("Static Constructor called");
}
public Program()
{
Console.WriteLine("Instance Constructor called");
}
public static void Main()
{
Program P = new Program();
}
}
}
namespace TestConsole
{
class Program
{
static int I;
static Program()
{
I = 100;
Console.WriteLine("Static Constructor called");
}
public Program()
{
Console.WriteLine("Instance Constructor called");
}
public static void Main()
{
Program P = new Program();
}
}
}
Can you mark static
constructor with access modifiers?
No, we cannot use access modifiers on static constructor.
Can you have parameters for static constructors?
No, static constructors cannot have parameters.
What happens if a static constructor throws an exception?
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.
Give 2 scenarios where static constructors can be used?
1. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
2. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
Does C# provide copy constructor?
No, C# does not provide copy constructor.
No, we cannot use access modifiers on static constructor.
Can you have parameters for static constructors?
No, static constructors cannot have parameters.
What happens if a static constructor throws an exception?
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.
Give 2 scenarios where static constructors can be used?
1. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
2. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
Does C# provide copy constructor?
No, C# does not provide copy constructor.
What is .NET Remoting?
.NET Remoting allows objects to interact with one another across application domains.
What are the 2 message encoding formats supported by .NET Remoting and when do you choose one over the other?
Message Encoding Formats:
1. Binary encoding.
2. XML encoding.
Applications can use binary encoding where performance is critical, or XML encoding where interoperability with other remoting frameworks is essential.
What are the two types of .NET remote objects?
1. Client-activated objects - Client-activated objects are under the control of a lease-based lifetime manager that ensures that the object is garbage collected when its lease expires.
2. Server-activated objects - In the case of server-activated objects, developers have a choice of selecting either a "single call" or "singleton" model. The lifetime of singletons are also controlled by lease-based lifetime.
What is considered as Remote Object?
Any object outside the application domain of the calling appication is considered remote object, even if the objects are executing on the same machine.
Can you treat every object as a remote object?
Objects that cannot be serialized cannot be passed to a different application domain and are therefore nonremotable.
What are the ways in which an object can be serialized?
1. Mark your class with serializable attribute.
2. Make your class implement ISerializable interface.
How can you change an object into a remote object?
Any object can be changed into a remote object by deriving it from MarshalByRefObject.
What happens when a client activates a remote object?
When a client activates a remote object, it receives a proxy to the remote object. All operations on this proxy are appropriately indirected to enable the remoting infrastructure to intercept and forward the calls appropriately.
What are proxy objects and what is the use of these proxy objects?
Proxy objects are created when a client activates a remote object. The proxy object acts as a representative of the remote object and ensures that all calls made on the proxy are forwarded to the correct remote object instance.
What is the difference between method parameters and method arguments. Give an example?
In the example below FirstNumber and SecondNumber are method parameters where as FN and LN are method arguments. The method definition specifies the names and types of any parameters that are required. When calling code calls the method, it provides concrete values called arguments for each parameter. The arguments must be compatible with the parameter type but the argument name (if any) used in the calling code does not have to be the same as the parameter named defined in the method.
.NET Remoting allows objects to interact with one another across application domains.
What are the 2 message encoding formats supported by .NET Remoting and when do you choose one over the other?
Message Encoding Formats:
1. Binary encoding.
2. XML encoding.
Applications can use binary encoding where performance is critical, or XML encoding where interoperability with other remoting frameworks is essential.
What are the two types of .NET remote objects?
1. Client-activated objects - Client-activated objects are under the control of a lease-based lifetime manager that ensures that the object is garbage collected when its lease expires.
2. Server-activated objects - In the case of server-activated objects, developers have a choice of selecting either a "single call" or "singleton" model. The lifetime of singletons are also controlled by lease-based lifetime.
What is considered as Remote Object?
Any object outside the application domain of the calling appication is considered remote object, even if the objects are executing on the same machine.
Can you treat every object as a remote object?
Objects that cannot be serialized cannot be passed to a different application domain and are therefore nonremotable.
What are the ways in which an object can be serialized?
1. Mark your class with serializable attribute.
2. Make your class implement ISerializable interface.
How can you change an object into a remote object?
Any object can be changed into a remote object by deriving it from MarshalByRefObject.
What happens when a client activates a remote object?
When a client activates a remote object, it receives a proxy to the remote object. All operations on this proxy are appropriately indirected to enable the remoting infrastructure to intercept and forward the calls appropriately.
What are proxy objects and what is the use of these proxy objects?
Proxy objects are created when a client activates a remote object. The proxy object acts as a representative of the remote object and ensures that all calls made on the proxy are forwarded to the correct remote object instance.
What is the difference between method parameters and method arguments. Give an example?
In the example below FirstNumber and SecondNumber are method parameters where as FN and LN are method arguments. The method definition specifies the names and types of any parameters that are required. When calling code calls the method, it provides concrete values called arguments for each parameter. The arguments must be compatible with the parameter type but the argument name (if any) used in the calling code does not have to be the same as the parameter named defined in the method.
Code:
using System;
namespace Demo
{
class Program
{
public static void Main()
{
int FN = 10;
int SN = 20;
//FN and LN are method arguments
int Total = Sum(FN, SN);
Console.WriteLine(Total);
}
//FirstNumber and SecondNumber are method parameters
public static int Sum(int FirstNumber, int SecondNumber)
{
int Result = FirstNumber + SecondNumber;
return Result;
}
}
}
namespace Demo
{
class Program
{
public static void Main()
{
int FN = 10;
int SN = 20;
//FN and LN are method arguments
int Total = Sum(FN, SN);
Console.WriteLine(Total);
}
//FirstNumber and SecondNumber are method parameters
public static int Sum(int FirstNumber, int SecondNumber)
{
int Result = FirstNumber + SecondNumber;
return Result;
}
}
}
Can you pass value types by reference to a method?
Yes, we can pass value types by by reference to a method. An example is shown below.
Code:
using System;
namespace Demo
{
class Program
{
public static void Main()
{
int I = 10;
Console.WriteLine("Value of I before passing to the method = " + I);
Function(ref I);
Console.WriteLine("Value of I after passing to the method by reference= " + I);
}
public static void Function(ref int Number)
{
Number = Number + 5;
}
}
}
namespace Demo
{
class Program
{
public static void Main()
{
int I = 10;
Console.WriteLine("Value of I before passing to the method = " + I);
Function(ref I);
Console.WriteLine("Value of I after passing to the method by reference= " + I);
}
public static void Function(ref int Number)
{
Number = Number + 5;
}
}
}
What is the difference between static class and class with static methods? In which case I should use either of them?
If your class has only static members you never need an instance of that class so you should make the class itself static but if your class has instance members (non static) then you have to make your class an instance class to access its instance members via instances of your class.
If a method's return type is void, can you use a return keyword in the method?
Yes, Even though a method's return type is void, you can use the return keyword to stop the execution of the method as shown in the example below.
Code:
using System;
namespace Demo
{
class Program
{
public static void Main()
{
SayHi();
}
public static void SayHi()
{
Console.WriteLine("Hi");
return;
Console.WriteLine("This statement will never be executed");
}
}
}
namespace Demo
{
class Program
{
public static void Main()
{
SayHi();
}
public static void SayHi()
{
Console.WriteLine("Hi");
return;
Console.WriteLine("This statement will never be executed");
}
}
}
How do you create empty strings in C#?
Using string.empty as shown in the example below.
string EmptyString = string.empty;
What is the difference between System.Text.StringBuilder and System.String?
1. Objects of type StringBuilder are mutable where as objects of type System.String are immutable.
2. As StringBuilder objects are mutable, they offer better performance than string objects of type System.String.
3. StringBuilder class is present in System.Text namespace where String class is present in System namespace.
What is the difference between int.Parse and int.TryParse methods?
Parse method throws an exception if the string you are trying to parse is not a valid number where as TryParse returns false and does not throw an exception if parsing fails. Hence TryParse is more efficient than Parse.
What is the difference between string keyword and System.String class?
string keyword is an alias for Syste.String class. Therefore, System.String and string keyword are the same, and you can use whichever naming convention you prefer. The String class provides many methods for safely creating, manipulating, and comparing strings.
Are string objects mutable or immutable?
String objects are immutable.
What do you mean by String objects are immutable?
String objects are immutable means, they cannot be changed after they have been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new string object. In the following example, when the contents of s1 and s2 are concatenated to form a single string, the two original strings are unmodified. The += operator creates a new string that contains the combined contents. That new object is assigned to the variable s1, and the original object that was assigned to s1 is released for garbage collection because no other variable holds a reference to it.
Code:
string s1 =
"First String ";
string s2 = "Second String";
// Concatenate s1 and s2. This actually creates a new
// string object and stores it in s1, releasing the
// reference to the original object.
s1 += s2;
System.Console.WriteLine(s1);
// Output: First String Second String
string s2 = "Second String";
// Concatenate s1 and s2. This actually creates a new
// string object and stores it in s1, releasing the
// reference to the original object.
s1 += s2;
System.Console.WriteLine(s1);
// Output: First String Second String
What is an array?
An array is a data structure that contains several variables of the same type.
What are the 3 different types of arrays?
1. Single-Dimensional
2. Multidimensional
3. Jagged
What is Jagged Array?
A jagged array is an array of arrays.
Are arrays value types or reference types?
Arrays are reference types.
What is the base class for Array types?
System.Array
Can you use foreach iteration on arrays in C#?
Yes,Since array type implements IEnumerable, you can use foreach iteration on all arrays in C#.
What is Boxing and Unboxing?
Boxing - Converting a value type to reference type is called boxing. An example is shown below.
Code:
int i = 101;
object obj = (object)i; // Boxing
object obj = (object)i; // Boxing
Unboxing - Converting
a reference type to a value typpe is called unboxing. An example is shown
below.
Code:
obj = 101;
i = (int)obj; // Unboxing
i = (int)obj; // Unboxing
Is boxing an implicit conversion?
Yes, boxing happens implicitly.
Is unboxing an implicit conversion?
No, unboxing is an explicit conversion.
What happens during the process of boxing?
Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object. Due to this boxing and unboxing can have performance impact.
What are the 4 pillars of any object oriented programming language?
1. Abstraction
2. Inheritance
3. Encapsulation
4. Polymorphism
Do structs support inheritance?
No, structs do not support inheritance, but they can implement interfaces.
What is the main advantage of using inheritance?
Code reuse
Does C# support multiple class inheritance?
No, C# supports single class inheritance only. However classes can implement multiple interfaces at the same time.
What is an abstract class?
An abstract class is an incomplete class and must be implemented in a derived class.
Can you create an instance of an abstract class?
No, abstract classes are incomplete and you cannot create an instance of an abstract class.
What is a sealed class?
A sealed class is a class that cannot be inherited from. This means, If you have a class called Customer that is marked as sealed. No other class can inherit from Customer class. For example, the below code generates a compile time error "MainClass cannot derive from sealed type Customer.
Code:
using System;
public sealed class Customer
{
}
public class MainClass : Customer
{
public static void Main()
{
}
}
public sealed class Customer
{
}
public class MainClass : Customer
{
public static void Main()
{
}
}
What are abstract
methods?
Abstract methods are methods that only the declaration of the method and no implementation.
Can a sealed class be used as a base class?
No, sealed class cannot be used as a base class. A compile time error will be generated.
Explain polymorphism in C# with a simple example?
Polymorphism allows you to invoke derived class methods through a base class reference during run-time. An example is shown below.
Abstract methods are methods that only the declaration of the method and no implementation.
Can a sealed class be used as a base class?
No, sealed class cannot be used as a base class. A compile time error will be generated.
Explain polymorphism in C# with a simple example?
Polymorphism allows you to invoke derived class methods through a base class reference during run-time. An example is shown below.
Code:
using System;
public class DrawingObject
{
public virtual void Draw()
{
Console.WriteLine("I am a drawing object.");
}
}
public class Triangle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Triangle.");
}
}
public class Circle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Circle.");
}
}
public class Rectangle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Rectangle.");
}
}
public class DrawDemo
{
public static void Main()
{
DrawingObject[] DrawObj = new DrawingObject[4];
DrawObj[0] = new Triangle();
DrawObj[1] = new Circle();
DrawObj[2] = new Rectangle();
DrawObj[3] = new DrawingObject();
foreach (DrawingObject drawObj in DrawObj)
{
drawObj.Draw();
}
}
}
public class DrawingObject
{
public virtual void Draw()
{
Console.WriteLine("I am a drawing object.");
}
}
public class Triangle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Triangle.");
}
}
public class Circle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Circle.");
}
}
public class Rectangle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Rectangle.");
}
}
public class DrawDemo
{
public static void Main()
{
DrawingObject[] DrawObj = new DrawingObject[4];
DrawObj[0] = new Triangle();
DrawObj[1] = new Circle();
DrawObj[2] = new Rectangle();
DrawObj[3] = new DrawingObject();
foreach (DrawingObject drawObj in DrawObj)
{
drawObj.Draw();
}
}
}
When can a derived
class override a base class member?
A derived class can override a base class member only if the base class member is declared as virtual or abstract.
What is the difference between a virtual method and an abstract method?
A virtual method must have a body where as an abstract method should not have a body.
Can fields inside a class be virtual?
No, Fields inside a class cannot be virtua. Only methods, properties, events and indexers can be virtual.
What are Access Modifiers in C#?
In C# there are 5 different types of Access Modifiers.
Public
The public type or member can be accessed by any other code in the same assembly or another assembly that references it.
Private
The type or member can only be accessed by code in the same class or struct.
Protected
The type or member can only be accessed by code in the same class or struct, or in a derived class.
Internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.
Protected Internal
The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.
What are Access Modifiers used for?
Access Modifiers are used to control the accessibilty of types and members with in the types.
Can you use all access modifiers for all types?
No, Not all access modifiers can be used by all types or members in all contexts, and in some cases the accessibility of a type member is constrained by the accessibility of its containing type.
Can derived classes have greater accessibility than their base types?
No, Derived classes cannot have greater accessibility than their base types. For example the following code is illegal.
A derived class can override a base class member only if the base class member is declared as virtual or abstract.
What is the difference between a virtual method and an abstract method?
A virtual method must have a body where as an abstract method should not have a body.
Can fields inside a class be virtual?
No, Fields inside a class cannot be virtua. Only methods, properties, events and indexers can be virtual.
What are Access Modifiers in C#?
In C# there are 5 different types of Access Modifiers.
Public
The public type or member can be accessed by any other code in the same assembly or another assembly that references it.
Private
The type or member can only be accessed by code in the same class or struct.
Protected
The type or member can only be accessed by code in the same class or struct, or in a derived class.
Internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.
Protected Internal
The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.
What are Access Modifiers used for?
Access Modifiers are used to control the accessibilty of types and members with in the types.
Can you use all access modifiers for all types?
No, Not all access modifiers can be used by all types or members in all contexts, and in some cases the accessibility of a type member is constrained by the accessibility of its containing type.
Can derived classes have greater accessibility than their base types?
No, Derived classes cannot have greater accessibility than their base types. For example the following code is illegal.
Code:
using System;
internal class InternalBaseClass
{
public void Print()
{
Console.WriteLine("I am a Base Class Method");
}
}
public class PublicDerivedClass : InternalBaseClass
{
public static void Main()
{
Console.WriteLine("I am a Public Derived Class Method");
}
}
internal class InternalBaseClass
{
public void Print()
{
Console.WriteLine("I am a Base Class Method");
}
}
public class PublicDerivedClass : InternalBaseClass
{
public static void Main()
{
Console.WriteLine("I am a Public Derived Class Method");
}
}
When
you compile the above code an error will be generated stating "Inconsistent
accessibility: base class InternalBaseClass is less accessible than class
PublicDerivedClass".To make this simple, you cannot have a public
class B that derives from an internal class A. If this were allowed, it would
have the effect of making A public, because all protected or internal members
of A are accessible from the derived class.
Can you declare struct members as protected?
No, struct members cannot be declared protected. This is because structs do not support inheritance.
Can the accessibility of a type member be greater than the accessibility of its containing type?
No, the accessibility of a type member can never be greater than the accessibility of its containing type. For example, a public method declared in an internal class has only internal accessibility.
Can destructors have access modifiers?
No, destructors cannot have access modifiers.
What does protected internal access modifier mean?
The protected internal access means protected OR internal, not protected AND internal. In simple terms, a protected internal member is accessible from any class in the same assembly, including derived classes. To limit accessibility to only derived classes in the same assembly, declare the class itself internal, and declare its members as protected.
What is the default access modifier for a class,struct and an interface declared directly with a namespace?
internal
Can you specify an access modifier for an enumeration?
Enumeration members are always public, and no access modifiers can be specified.
Can you declare struct members as protected?
No, struct members cannot be declared protected. This is because structs do not support inheritance.
Can the accessibility of a type member be greater than the accessibility of its containing type?
No, the accessibility of a type member can never be greater than the accessibility of its containing type. For example, a public method declared in an internal class has only internal accessibility.
Can destructors have access modifiers?
No, destructors cannot have access modifiers.
What does protected internal access modifier mean?
The protected internal access means protected OR internal, not protected AND internal. In simple terms, a protected internal member is accessible from any class in the same assembly, including derived classes. To limit accessibility to only derived classes in the same assembly, declare the class itself internal, and declare its members as protected.
What is the default access modifier for a class,struct and an interface declared directly with a namespace?
internal
Can you specify an access modifier for an enumeration?
Enumeration members are always public, and no access modifiers can be specified.
No comments:
Post a Comment