Technical Q&A [C#]

Solarion

Honorary Master
Joined
Nov 14, 2012
Messages
21,885
See how you do. Please feel free to add more.

1. What is C#?
2. What are the types of comment in C# with examples?
3. Can multiple catch blocks be executed?
4. What is the difference between public, static and void?
5. What is an object?
6. Define Constructors?
7. What is Jagged Arrays?
8. What is the difference between ref & out parameters?
9. What is the use of using statement in C#?
10. What is serialization?
11. Can “this” be used within a static method?
12. What is difference between constants and read-only?
13. What is an interface class?
14. What are value types and reference types?
15. What are Custom Control and User Control?
16. What are sealed classes in C#?
17. What is method overloading?
18. What is the difference between Array and Arraylist?
19. Can a private virtual method be overridden?
20. Describe the accessibility modifier “protected internal”
21. What are the differences between System.String and System.Text.StringBuilder classes?
22. What’s the difference between the System.Array.CopyTo() and System.Array.Clone() ?
23. How can we sort the elements of the array in descending order?
24. Write down the C# syntax to catch exception?
25. What’s the difference between an interface and abstract class?
26. What is the difference between Finalize() and Dispose() methods?
27. What are circular references?
28. What are generics in C#.NET?
29. What is an object pool in .NET?
30. List down the commonly used types of exceptions in .Net?
31. What are Custom Exceptions?
32. What are delegates?
33. How do you inherit a class into other class in C#?
34. What is the base class in .net from which all the classes are derived from?
35. What is the difference between method overriding and method overloading?
36. What are the different ways a method can be overloaded?
37. Why can’t you specify the accessibility modifier for methods inside the interface?
38. How can we set class to be inherited, but prevent the method from being over-ridden?
39. What happens if the inherited interfaces have conflicting method names?
40. What is the difference between a Struct and a Class?
41. How to use nullable types in .Net?
42. How we can create an array with non-default values?
43. What is difference between is and as operators in c#?
44. What’s a multicast delegate?
45. What are indexers in C# .NET?
46. What is difference between the “throw” and “throw ex” in .NET?
47. What are C# attributes and its significance?
48. How to implement singleton design pattern in C#?
49. What is the difference between directcast and ctype?
50. Is C# code is managed or un-managed code?

There is also a quiz at the bottom of this page

http://career.guru99.com/top-50-c-sharp-interview-questions-answers/
 

_kabal_

Executive Member
Joined
Oct 24, 2005
Messages
5,922
What is the difference between public, static and void

Who comes up with this ***?
What is the difference between a bowl of custard and the number 43?
:p
 

Ancalagon

Honorary Master
Joined
Feb 23, 2010
Messages
18,140
50. Is C# code is managed or un-managed code?

Besides the obvious grammatical mistake, C# as a language is neither managed or unmanaged. What matters in this case is the compiler. Theoretically it would be possible for someone to write a compiler that takes in C# and produces a native ARMv7 binary - which would definitely be unmanaged.

It just so happens that the most commonly used C# compiler produces object code compatible with the .NET platform. However, managed or unmanaged is still not a property of C# code itself - it is a property of the entire platform.
 

Solarion

Honorary Master
Joined
Nov 14, 2012
Messages
21,885
I've got a nice one. What do you use to encapsulate methods? It also supports multi casting.
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
Since C# 3.0 delegate builtins for Func & Action, there hardly ever a good reason to define your own delegates for common use. This is after all similar to type aliasing, sadly just not as flexible. Also what's called multi casting is just a poor substitute for composition.

Sadly Microsoft does this too often, giving different names to common features in Functional Programming, same e.g. with Linq:
  • Select = map
  • Aggregate = fold
  • SelectMany = flatmap
 
Last edited:

Solarion

Honorary Master
Joined
Nov 14, 2012
Messages
21,885
@roi - I found this, is this what you're talking about?

PHP:
class MethodCollections  
    {  
  
        //Methods that takes parameters but returns nothing:  
   
        public static void PrintText()  
        {  
            Console.WriteLine("Text Printed with the help of Action");  
        }  
        public static void PrintNumbers(int start, int target)  
        {  
            for (int i = start; i <= target; i++)  
            {  
                Console.Write(" {0}",i);  
            }  
            Console.WriteLine();  
        }  
        public static void Print(string message)  
        {  
            Console.WriteLine(message);  
        }  
  
        //Methods that takes parameters and returns a value:  
  
        public static int Addition(int a, int b)  
        {  
            return a + b;  
        }  
  
        public static string DisplayAddition(int a, int b)  
        {  
            return string.Format("Addition of {0} and {1} is {2}",a,b,a+b);  
        }  
  
        public static string SHowCompleteName(string firstName, string lastName)  
        {  
            return string.Format("Your Name is {0} {1}",firstName,lastName);  
        }  
        public static int ShowNumber()  
        {  
            Random r = new Random();  
            return r.Next();  
        }  
    }

PHP:
class Program  
    {  
        static void Main(string[] args)  
        {  
            Action printText = new Action(MethodCollections.PrintText);  
            Action<string> print = new Action<string>(MethodCollections.Print);  
            Action<int, int> printNumber = new Action<int, int>(MethodCollections.PrintNumbers);  
  
            Func<int, int,int> add1 = new Func<int, int, int>(MethodCollections.Addition);  
            Func<int, int, string> add2 = new Func<int, int, string>(MethodCollections.DisplayAddition);  
            Func<string, string, string> completeName = new Func<string, string, string>(MethodCollections.SHowCompleteName);  
            Func<int> random = new Func<int>(MethodCollections.ShowNumber);  
  
            Console.WriteLine("\n***************** Action<> Delegate Methods ***************\n");  
            printText();    //Parameter: 0 , Returns: nothing  
            print("Abhishek");  //Parameter: 1 , Returns: nothing  
            printNumber(5, 20); //Parameter: 2 , Returns: nothing  
            Console.WriteLine();  
            Console.WriteLine("**************** Func<> Delegate Methods *****************\n");  
            int addition = add1(2, 5);  //Parameter: 2 , Returns: int  
            string addition2 = add2(5, 8);  //Parameter: 2 , Returns: string  
            string name = completeName("Adam", "Wilson");    //Parameter:2 , Returns: string  
            int randomNumbers = random();   ////Parameter: 0 , Returns: int  
  
            Console.WriteLine("Addition: {0}",addition);  
            Console.WriteLine(addition2);  
            Console.WriteLine(name);  
            Console.WriteLine("Random Number is: {0}",randomNumbers);  
  
            Console.ReadLine();  
        }  
    }
 

Solarion

Honorary Master
Joined
Nov 14, 2012
Messages
21,885
Off hand, I can't think of a single use for delegates at the moment.

Event Handling is a type of delegate right?
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
Sort of; the real uses are far more versatile though.
Btw in most cases you can avoid the doubling up of type signatures by using "var" i.e. type inference as opposed to fixed typing, for example:

Instead of this:
PHP:
Func<int, int,int> add1 = new Func<int, int, int>(MethodCollections.Addition);

Rewrite it like this with 'var' to force type inference:
PHP:
var add1 = new Func<int, int, int>(MethodCollections.Addition);

The type system in C# is still a bit disjointed, here's an example extended from this static method:
PHP:
static int add(int op1, int op2) {
  return op1 + op2;
}

The following 3 examples are exactly the same:
PHP:
Func<int, int, int> add1 = add;
var add2 = new Func<int, int, int>(add);
var add3 = (Func<int, int, int>)add;
I.e. Their output and behavior is exactly the same:
PHP:
Console.WriteLine(add(1, 1)); // 2
Console.WriteLine(add1(1, 1)); // 2
Console.WriteLine(add2(1, 1)); // 2
Console.WriteLine(add3(1, 1)); // 2

However this doesn't work:
PHP:
var add4 = add;
Ideally C# should see this the same as the others, and infer it as a function that takes 2 'int's and return a 'int'.
I.e. (int, int) => int or in C# type syntax it should be inferred to be Func<int, int, int>
 
Last edited:

Solarion

Honorary Master
Joined
Nov 14, 2012
Messages
21,885
Ok getting the hang of it now. These are mostly used for type safety right? Honestly the code just looks a lot cleaner and more straight forward having the class's methods wrapped up in delegates.
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
Ok getting the hang of it now. These are mostly used for type safety right? Honestly the code just looks a lot cleaner and more straight forward having the class's methods wrapped up in delegates.
Type safety is part of C#'s language design, more specifically; it's statically typed, which simply means that type constraints are enforced at compile-time instead of run-time. Not sure I understand what you mean by "looks a lot cleaner and more straight forward having the class's methods wrapped up in delegates".

The versatility of all of this resides in functions being treated as first class functions i.e. No different than variables, the uses are very diverse, however a simple example is being able to use a function as input to a parameter, and then similar to dependency injection; inject exchangeable functions into other functions, etc...

DI example using first class functions
PHP:
static int Add(int op1, int op2) {
  return op1 + op2;
}

static int Multiply(int op1, int op2) {
  return op1 * op2;
}

static string Calculate(Func<int, int, int> function, int op1, int op2) {
  return string string.Format("{0}, {1} == {2} ", op1, op2, function(op1, op2));
}

Console.WriteLine(Calculate(Add, 2, 4));  // 2, 4 == 6
Console.WriteLine(Calculate(Multiply, 2, 4)); // 2, 4 == 8

In short first class functions make functions behave the same as variables, which exposes a multitude of possibilities. For example:
  • you can box them in class instances, similar to dependency injection
  • enclosed them in array structures, and treat them like data
  • or even add them together (composition)
  • etc...
 
Last edited:

Spacerat

Expert Member
Joined
Jul 29, 2015
Messages
1,328
Yes this is quite powerful. I implemented a messenger that can broadcast messages. Used it to message between ViewModels.

The subscribers just registered an Action<T> with the messenger. When a message is sent, all the subscribed Actions are invoked. Optionally synced to the UI thread. Although, instead of an Action, I used WeakAction. So a subscriber can subscribe and then be disposed by another party. The WeakAction prevents the action invocation on a null or disposed object from failing...
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
Yes this is quite powerful. I implemented a messenger that can broadcast messages. Used it to message between ViewModels.

The subscribers just registered an Action<T> with the messenger. When a message is sent, all the subscribed Actions are invoked. Optionally synced to the UI thread. Although, instead of an Action, I used WeakAction. So a subscriber can subscribe and then be disposed by another party. The WeakAction prevents the action invocation on a null or disposed object from failing...
What you describe is the default behavior for flatmap' on an Optional type; which can either contain a value or be empty (null).
 
Last edited:

Spacerat

Expert Member
Joined
Jul 29, 2015
Messages
1,328
[)roi(];19077996 said:
What you describe is the default behavior for flatmap' on an Optional type; which can either contain a value or be empty (null).

Not sure if the same though? C# also have nullable types.
But if you reference a null object, you will get exception.

In this particular case you have a valid reference to an object in memory. The GC cannot dispose the object referenced to, leading to memory leaks. But using a weak reference, the GC can garbage collect it. Then also when you use this reference, it knows it's stale (the target is disposed) and ignores it.
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
Not sure if the same though? C# also have nullable types.
But if you reference a null object, you will get exception.

In this particular case you have a valid reference to an object in memory. The GC cannot dispose the object referenced to, leading to memory leaks. But using a weak reference, the GC can garbage collect it. Then also when you use this reference, it knows it's stale (the target is disposed) and ignores it.
C# nullable types aren't optionals; but rather extending nulls to primitives. The implementation misses all the benefits of real Optional types. Creating an optional type is however fairly easy to do; plus there are quite a few functional C# libs for this.

As for weak binding; yip I understood that; common approach with UI and Closures. It's a simply a different approach, but the behaviour is the same.
 
Last edited:

Spacerat

Expert Member
Joined
Jul 29, 2015
Messages
1,328
[)roi(];19081466 said:
C# nullable types aren't optionals; but rather extending nulls to primitives. The implementation misses all the benefits of real Optional types. Creating an optional type is however fairly easy to do; plus there are quite a few functional C# libs for this.

Yes true, but there are some new C# syntax/features that implements/syntactic sugar for true Optional types. At least that is AFAIR
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
Yes true, but there are some new C# syntax/features that implements/syntactic sugar for true Optional types. At least that is AFAIR

FYI Microsoft has acknowledged the current limitations and committed to improving it in a future release; but still not all design decisions can be undone.

As for the extended Optional type features like 'map', 'flatmap', etc. -- it's anyone's guess if they're cover that aspect with Linq e.g. Select, SelectMany

Mads Torgersen said:
Torgersen: This is something that Miguel de Icaza feels strongly about and so do we. We actually do have a sketch of a feature that we want to do, it won’t be in the next version, but we are thinking the one after. Null pointers are there to stay, they are an integral part of the semantics of the language, but we should let you state your intent. Is this this return type, or field type, or whatever, is this supposed to be null or not?

So something like, put a question mark on the type if this thing is supposed to be null, and then start assuming that if you didn’t put the question mark it’s not intended to be null. We know its default value is going to be null, so we will check your constructors, do they make sure to overwrite the null before the object is constructed, we’ll check that you don’t assign nulls into it. And if you do put the question mark on and say yes, I will have the nulls, then we will start impeding you from de-referencing. We will say, you can’t dot [ie. de-reference] until you’ve proven to us that this is not null.

We have to do it in a way that we recognise the ways that people are already checking for null. Then if we see, oh you did that up there, we do a flow analysis and say OK, we trust you, you checked, you can go ahead and dot. And by the way, if we can’t figure it out, you can still tell us that you really want to do it.

So it is very much on our radar. It is one of those things we regret. The computer science grand old man, Tony Hoare, who actually worked for Microsoft Research for many years and still comes in on Thursdays, he gives a talk about his billion dollar mistake, how he invented the null pointer and wants to apologise.

http://www.theregister.co.uk/2016/05/19/mads_torgersen_and_dustin_campbell_on_the_future_of_c/
 
Last edited:
Top