Note : All of this content is taken from many important articles related to C# & important topics. I decided to create one point where all C# questions can be available.
Also read Theoretical/Logical C# Interview Question.
Q. Write a program in C# that take string input, and print its number of characters.
string name = Console.ReadLine(); Console.WriteLine(name.Length); Console.ReadLine();
Q. Write a program in C Sharp that take a sentense as input, and show the number of “a” used in the sentense.
string name = Console.ReadLine(); int counter = 0; for (int i = 0; i < name.Length; i++) { if (name[i] == 'a') { counter++; } } Console.WriteLine(counter); Console.ReadLine();
Q. Write a program in C# taht take name and password. If the name and password are correct, the program show “you are logged in”, otherwise, “incorrect name or password”.
Console.WriteLine("Enter your Name"); Console.WriteLine("Enter your Pswrd"); string name = Console.ReadLine(); string pswrd = Console.ReadLine(); string myname = "bilal"; string mypswrd = "123456"; if (name == myname && pswrd == mypswrd) { Console.WriteLine("You are logged in"); } else { Console.WriteLine("Incorrect name or pswrd"); } Console.ReadLine();
Sorting Arrays in C Sharp
Q. Write a string array of length 3, and sort them.
string[] name = new string[] { "We", "He", "Us"}; Array.Sort(name); foreach (string i in name) { Console.WriteLine(i); } Console.ReadLine();
Q. Write a string array in C# that take 5 inputs, and sort them.
string[] name = new string[5]; for (int i = 0; i < 5; i++) { name[i] = Console.ReadLine(); } Array.Sort(name); foreach (string i in name) { Console.WriteLine(i); } Console.ReadLine();
Q. Write an array in C Sharp of length 3, and sort it.
int[] numbers = new int [] { 4, 3, 8, 0, 5 }; Array.Sort(numbers); foreach (int i in numbers) { Console.WriteLine(i); } Console.ReadLine();
Q. Write a program in C# that take 5 integers, and sort them.
int[] numbers = new int[5]; for (int i = 0; i < 5; i++) { numbers[i] = Convert.ToInt16(Console.ReadLine()); } Array.Sort(numbers); foreach (int i in numbers) { Console.WriteLine(i); } Console.ReadLine();
Print Pattern in C-Sharp
Q. Print * 10 times vertically usinf C# Console Application.
for (int i = 1; i < 11; i++) { Console.WriteLine("*"); } Console.ReadLine(); Q. Print * 10 times Horizontally usinf C# Console Application. for (int i = 1; i < 11; i++) { Console.Write("*"); } Console.ReadLine();
Q. Print * 10 times Horizontally with spaces between them usinf C# Console Application.
for (int i = 1; i < 11; i++) { Console.Write("* "); } Console.ReadLine(); Q. Write a program in C# that take string input and print the result vertically. string name = Console.ReadLine(); for (int i = 0; i < name.Length; i++) { Console.WriteLine(name[i]); } Console.ReadLine();
Q. Print the Pyramid pattern using C# Console Application.
*
**
***
****
*****
for (int i = 1; i < 6; i++) { for (int j = 1; j <= i; j++) { Console.Write("*"); } Console.WriteLine(""); } Console.ReadLine();
Q. Print the following pattern using C-Sharp Console Application.
*****
****
***
**
*
for (int i = 5; i > 0; i--) { for (int j = 1; j <= i; j++) { Console.Write("*"); } Console.WriteLine(""); } Console.ReadLine();
Q. Print pyramid using C# Console Application, like this: *
* *
* * *
* * * *
* * * * *
* *
* * *
* * * *
* * * * *
for (int i = 1; i < 6; i++) { for (int j = 4; j >= i; j--) { Console.Write(" "); } for (int k = 1; k <= i; k++) { Console.Write("* "); } Console.WriteLine(""); } Console.ReadLine();
Q. What is the significance of Finalize method in .NET?
.NET Garbage collector does almost all clean up activity for your objects. But unmanaged resources (ex: - Windows API created objects, File, Database connection objects, COM objects etc) is outside the scope of .NET framework we have to explicitly clean our resources. For these types of objects, .NET framework provides Object. Finalize method, which can be overridden and clean up code for unmanaged resources can be put in this section
Q. Why is it preferred to not use finalize for clean up?
Problem with finalize is that garbage collection has to make two rounds in order to remove objects which have finalize methods. Below figure will make things clear regarding the two rounds of garbage collection rounds performed for the objects having finalized methods.
Q. What is the use of DISPOSE method?
Dispose method belongs to ‘IDisposable’ interface. We had seen in the previous section how bad it can be to override the finalize method for writing the cleaning of unmanaged resources. So if any object wants to release its unmanaged code best is to implement I Disposable and override the Dispose method of I Disposable interface. Now once your class has exposed the Dispose method it is the responsibility of the client to call the Dispose method to do the cleanup.
Q. How do I force the Dispose method to be called automatically, as clients can forget to call Dispose method?
Call the Dispose method in Finalize method and in Dispose method suppress the finalize method using GC.SuppressFinalize. Below is the sample code of the pattern. This is the best way we do clean our unallocated resources and yes not to forget we do not get the hit of running the Garbage collector twice. public class CleanClass : IDisposable { public void Dispose() { GC.SuppressFinalize(this); } protected override void Finalize() { Dispose(); } }
Q. What is an interface and what is an abstract class? Please, expand by examples of using both. Explain why.
Answers 1: In a interface class, all methods are abstract without implementation whereas in an abstract class some methods we can define concrete. In interface, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers. Interface and abstract class are basically a set of rules which u have to follow in case you are using them(inheriting them). Answers 2: Abstract classes are closely related to interfaces. They are classes that cannot be instantiated, and are frequently either partially implemented, or not at all implemented. One key difference between abstract classes and interfaces is that a class may implement an unlimited number of interfaces, but may inherit from only one abstract (or any other kind of) class. A class that is derived from an abstract class may still implement interfaces. Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code. Answers3: Abstract Classes An abstract class is the one that is not used to create objects. An abstract class is designed to act as a base class (to be inherited by other classes). Abstract class is a design concept in program development and provides a base upon which other classes are built. Abstract classes are similar to interfaces. After declaring an abstract class, it cannot be instantiated on it’s own, it must be inherited. Like interfaces, abstract classes can specify members that must be implemented in inheriting classes. Unlike interfaces, a class can inherit only one abstract class. Abstract classes can only specify members that should be implemented by all inheriting classes. Answers4: Interface An interface looks like a class, but has no implementation. They’re great for putting together plug-n-play like architectures where components can be interchanged at will. Think Firefox Plug-in extension implementation. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks. Answers5: One additional key difference between interfaces and abstract classes (possibly the most important one) is that multiple interfaces can be implemented by a class, but only one abstract class can be inherited by any single class. Some background on this: C++ supports multiple inheritance, but C# does not. Multiple inheritance in C++ has always be controversial, because the resolution of multiple inherited implementations of the same method from different base classes is hard to control and anticipate. C# decided to avoid this problem by allowing a class to implement multiple interfaces, which do not contain method implementations, but restricting a class to have at most a single parent class. Although this can result in redundant implementations of the same method when different classes implement the same interface, it is still an excellent compromise. Another difference between interfaces and abstract classes is that an interface can be implemented by an abstract class, but no class, abstract or otherwise, can be inherited by an interface.
Q. What is an Abstract class?
An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
Q. What is an Interface?
An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.
Example Class Hierarchy
Let’s assume the following simple class hierarchy with classes A, B and C for the discussions in this text. A is the super- or base class, B is derived from A and C is derived from class B. In some of the easier examples, we will only refer to a part of this class hierarchy.
Polymorphism, Method hiding and overriding :
One of the fundamental concepts of object oriented software development is polymorphism. The term polymorphism (from the Greek meaning “having multiple forms”) in OO is the characteristic of being able to assign a different meaning or usage to something in different contexts – specifically, to allow a variable to refer to more than one type of object.
Inherited Methods
A method Foo() which is declared in the base class A and not redeclared in classes B or C is inherited in the two subclasses
using System; namespace Polymorphism { class A { public void Foo() { Console.WriteLine("A::Foo()"); } } class B : A {} class Test { static void Main(string[] args) { A a = new A(); a.Foo(); // output --> "A::Foo()" B b = new B(); b.Foo(); // output --> "A::Foo()" } } }
The method Foo() can be overridden in classes B and C:
using System; namespace Polymorphism { class A { public void Foo() { Console.WriteLine("A::Foo()"); } } class B : A { public void Foo() { Console.WriteLine("B::Foo()"); } } class Test { static void Main(string[] args) { A a; B b; a = new A(); b = new B(); a.Foo(); // output --> "A::Foo()" b.Foo(); // output --> "B::Foo()" a = new B(); a.Foo(); // output --> "A::Foo()" } } }
There are two problems with this code.
The output is not really what we, say from Java, expected. The method Foo() is a non-virtual method. C# requires the use of the keyword virtual in order for a method to actually be virtual. Although the code compiles and runs, the compiler produces a warning: ...polymorphism.cs(11,15): warning CS0108: The keyword new is required on 'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()'
Virtual and Overridden Methods
Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.
using System; namespace Polymorphism { class A { public virtual void Foo() { Console.WriteLine("A::Foo()"); } } class B : A { public override void Foo() { Console.WriteLine("B::Foo()"); } } class Test { static void Main(string[] args) { A a; B b; a = new A(); b = new B(); a.Foo(); // output --> "A::Foo()" b.Foo(); // output --> "B::Foo()" a = new B(); a.Foo(); // output --> "B::Foo()" } } }
Method Hiding
Why did the compiler in the second listing generate a warning? Because C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:
using System; namespace Polymorphism { class A { public void Foo() { Console.WriteLine("A::Foo()"); } } class B : A { public new void Foo() { Console.WriteLine("B::Foo()"); } } class Test { static void Main(string[] args) { A a; B b; a = new A(); b = new B(); a.Foo(); // output --> "A::Foo()" b.Foo(); // output --> "B::Foo()" a = new B(); a.Foo(); // output --> "A::Foo()" } } }
Combining Method Overriding and Hiding
Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:
class A { public void Foo() {} } class B : A { public virtual new void Foo() {} }
A class C can now declare a method Foo() that either overrides or hides Foo() from class B:
class C : B { public override void Foo() {} // or public new void Foo() {} }