2. C# Interview Questions
C# interview questions
1. What’s the implicit name of the parameter that gets passed into the class’ set
method?
Value, and it’s datatype depends on whatever variable we’re changing.
2. How do you inherit from a class in C#? Place a colon and then the name of the base class. 3. Does C# support multiple inheritance?
No, use interfaces instead.
4. When you inherit a protected class-level variable, who is it available to? Classes in the same namespace.
5. Are private class-level variables inherited?
Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.
6. Describe the accessibility modifier protected internal.
It’s available to derived classes and classes within the same Assembly (and naturally from the base class it’s declared in).
7. C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write?
Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.
8. What’s the top .NET class that everything is derived from? System.Object.
When overriding, you change the method behavior for a derived class. Overloading
simply involves having a method with the same name within the class.
10. What does the keyword virtual mean in the method definition?
The method can be over-ridden.
11. Can you declare the override method static while the original method is non-static?
No, you can’t, the signature of the virtual method must remain the same, only the
keyword virtual is changed to keyword override.
12. Can you override private virtual methods?
No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.
13. Can you prevent your class from being inherited and becoming a base class
for some other classes?
Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class
WhateverBaseClassName. It’s the same concept as final class in Java.
14. Can you allow class to be inherited, but prevent the method from being over-ridden?
Yes, just leave the class public and make the method sealed.
15. What’s an abstract class?
A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited and have the methods over-ridden. Essentially, it’s a blueprint for a class without any implementation.
16. When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)?
When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.
It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes.
18. Why can’t you specify the accessibility modifier for methods inside the interface?
They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it’s public by default.
19. Can you inherit multiple interfaces?
Yes, why not.
20. And if they have conflicting method names?
It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.
21. What’s the difference between an interface and abstract class?
In the interface all methods must be abstract, in the abstract class some methods can
be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes.
22. How can you overload a method?
Different parameter data types, different number of parameters, different order of parameters.
23. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the
appropriate constructor) in the overloaded constructor definition inside the inherited class.
24. What’s the difference between System.String and System.StringBuilder classes?
System.String is immutable, System.StringBuilder was designed with the purpose of
25. Is it namespace class or class namespace?
The .NET class library is organized into namespaces. Each namespace contains a functionally related group of classes so natural namespace comes first.
Read all | Browse topics: .NET
28 Comments »
1. Regarding #4 . “When you inherit a protected class-level variable, who is it available to? Classes in the same namespace. ”
Wrong, the protected keyword in C# specifies that only classes that ultimately inherit from the class with a protected member can see that member.
Quote from the C# Programmer’s Reference (MSDN):
“protected - Access is limited to the containing class or types derived from the containing class.”
Tech Interviews comment by Richard Lowe
2. Again in #15 “What’s an abstract class? … Essentially, it’s a blueprint for a class without any implementation.”
Although an abstract class does not require implementations (it’s methods can be abstract) it *can* also offer implementations of methods (either virtual or not) which can be called in implementing classes.
Tech Interviews comment by Richard Lowe 3. Right you are, Richard. Thanks, I will update.
Tech Interviews comment by admin
4. #18 is misleading. You CAN implement an interface explicitly without the members being declared public in your class. The difference is that if the members are not public, they will only be available when you have a reference variable of the type of the interface pointing to you class
You implement them like so: void IDisposable.Dispose() {
// TODO: Add Class1.Dispose implementation }
5. Oh hi, I hope my comments were helpful - I’m not just some C# facist :) I would just hate to see a right answer disqualify a good candidate!
Tech Interviews comment by Richard Lowe
6. #18
If the members of the interface are not public, then even if you have an instance of that, how would you implement/override non-public members if you don’t have any access to them?
Tech Interviews comment by admin
7. Yeah, no problem, I always welcome suggestions and corrections. Especially this set of questions which I wrote myself, by taking notes from Microsoft’s Self-Training MCSD cert kit. Your comments make me go back to the books and online documentation. #4 and #15 I totally agree. #18 I will double check :-) Tech Interviews comment by admin
8. “If the members of the interface are not public, then even if you have an instance of that, how would you implement/override non-public members if you don’t have any access to them?”
Ah, you meant “public to references to the *interface*” so of course they must be publically visible. I read the original question as meaning “public to references to the class” which isn’t a necessity. That was my mis-read, sorry.
Tech Interviews comment by Richard Lowe
9. Is it namespace class or class namespace???
The .NET class library is organized into namespaces. Each namespace contains a functionally related group of classes so natural namespace comes first.
Tech Interviews comment by Andrew O
10. correction: “so natural namespace comes first” should be “so naturally namespace comes first”
Tech Interviews comment by Andrew O 11. for question 7,
C# does’t cancel the freebie constructor(parameter less constuctor).
it is goting to keep the parameter less constructor, even if you add any number of parameterised constructors.
Tech Interviews comment by Kishore
12. I believe that Kishore is wrong in comment number 11. C# behaves this way so that you can specify a class has *no* parameterless constructor. If Kishore were correct, then it would be impossible to implement a class without a parameterless (”default”) constructor.
Tech Interviews comment by MBearden
13. An interesting (and difficult) question to add would be: “How do you specify constructors in an interface?” Answer is “You cannot. C# does not allow constructor signatures to be specified in interface.” I don’t know the reason why… If anyone reading this does, could you e-mail with your comments on why C# was designed this way? Just curious. Tech Interviews comment by MBearden
14. For Question 13:
As far I know interfaces doesn’t have data members(fields), they will only have methods or properties, so no need for constructors. I am also new to C# so I dont know whether I am completely correct or not.
Tech Interviews comment by ram 15. Follow up for #13 & #17
Ram, you are right. An instance of an interface cannot be created. (But the interface methods can be accessed in a class implementing that interface, by casting the instance of that class to the interface type. This is sometimes referred to as creating an instance of the interface.) “The job of a constructor is to create the object specified by a class and to put it into a valid state.”[Programming C#-Jesse Liberty]. So, no need of a constructor.
Use of property in an interface:
An interface can have methods, properties, events and indexers. When a property in an interface is implemented in a class,
the advantage is that, through that property, the class can give access to its private member varibles.
Hope Iam clear. Thanks,RAD
Tech Interviews comment by Rad
1) This question would be better stated “What is the implicit name of the parameter passed into a property’s ’set’ method?”
2) It’s a good while since I’ve had to do any C++, but my long term memory tells me that it isn’t double colon in C++. Perhaps you’re confusing the scope
resolution operator?
3) A better answer would be that C# disallows multiple inheritance of implementation, but allows classes to implement multiple interfaces.
4) This is just wrong. Protected members are visible only to classes that are derived from the containing class.
15) An abstract class in C++ is a class that contains at least 1 pure virtual method. Tech Interviews comment by Tim Haughton
17. can anyone explain/differentiate between different database concepts(odbc,ole-db,ado.net, ado,dao,rao)?
Tech Interviews comment by Kiran Mandhadi 18. Here are more questions
1. What does the readonly keyword do for a variable in c#? (hint on Question 4) 2. Can we overload methods by specifying different return types?
3. Can you can specify values for for variables in interfaces in c#? (In Java you can)
4. What is the difference between const and readonly ? Have Fun :)
Tech Interviews comment by Binoj Antony 19. Answers to Binoj’s Questions:
What does the readonly keyword do for a variable in c#? What is the difference between const and readonly ?
Answer) To declare constants in C# the const keyword is used for compile time constants while the readonly keyword is used for runtime constants
Can we overload methods by specifying different return types? Answer) NO. I tried it in VS.net
Can you can specify values for for variables in interfaces in c#? (In Java you can) Answer) Yes! I am not sure of this answer, correct me if I am wrong.
Would appreciate if anybody else could post more messages here Thanks, Kiran.
Tech Interviews comment by Kiran Mandhadi
20. Can you can specify values for for variables in interfaces in c#? (In Java you can) Answer) NO. I tried this in VS.net and it gave me the following error:
D:\VisualStudio\…\Interface.cs(10): Interfaces cannot contain fields Tech Interviews comment by Kiran Mandhadi
21. #12 The .Net compiler does not accept a virtual private method which makes sense since a virtual private method makes no sense.
Thanks, Laura
Tech Interviews comment by Laura Hunt 22. Another response to #13:
Since you constructors are not allowed in an interface, how would you be able to use an interface as a type parameter when the type parameter is constrained by new()?
Tech Interviews comment by Ike
23. This is regarding question #5, if u can’t access a member in derived class, then how do we say it is inherited.To my knowledge, the fundamental concept behind inheritance is representing the parent, if a child con’t access then we can say its not inherited.Please correct me if am wrong.
Tech Interviews comment by surendra 24. here’s a question I was asked at an interview:
What methods are called when a windows app is run and in what order are they called?
1. main
2. an instance of the form 3. form load
4. Initialize component 5. Dispose
what am I forgetting?
Tech Interviews comment by Andy 25. “Another response to #13:
Since you constructors are not allowed in an interface, how would you be able to use an interface as a type parameter when the type parameter is constrained by new()?”
You can’t. But, if the generic class requires the type to have a default constructor, that means it plans on creating an instance of that type at some point; and since you cant create an instance of an interface, it wouldnt make any sense to use an interface as the type parameter.
“This is regarding question #5, if u can’t access a member in derived class, then how do we say it is inherited.To my knowledge, the fundamental concept behind inheritance is representing the parent, if a child con’t access then we can say its not inherited.Please correct me if am wrong.”
Technically, saying that a particular item is inherited means that it still exists in the derived class. In .NET this is always the case: if I have a private field in my base class, then when I instantiate my derived class, space is reserved on the heap for the private field, even though my derived class cannot access it directly. This is somewhat confusing, and makes for a bad interview question, because it is not clear whether the interviewer is asking if the private member still exists in the derived class, or if the derived class can access the private member.
Tech Interviews comment by David 26. with regards to question #7:
The default (parameterless) constructor is not implicitly canceled by C# simply by virtue of you writing one that requires a parameter. Though for ease of use you SHOULD implement default behavior and initialisations in the default
constructor, unless parameters are absolutely required for initialisation. Which would only be necessary in the event of a lack of get/set properties for
private/protected member variables. hope that makes sense.
Jimbobob
27. oh yeah, and unless you intentionally erase the default consturctor in the code, it’ll stay there and stay functional.
Tech Interviews comment by Jimbobob
28. On question 14, it should be noted that only overridden methods can be sealed Tech Interviews comment by Phil Curran
---C# is one of the most visible aspects of Microsoft's .NET initiative. Developers
commonly see the world through the lens of their language, and so C# can be their main aperture into .NET. Misconceptions abound, however. In this article, I'd like to address the confusions I hear most often about this new tool.
• Which is better: C# or Java? The two languages have an awful lot in common,
and so in some ways it's natural to try to choose a winner. The fact that each language is often viewed as the flagship of its camp—C# in Microsoft's .NET environment, with Java supported by everybody else—makes the comparison especially attractive. But it's the wrong question. Not only is there no objective answer, it wouldn't matter if there were. To see why, realize that both languages are in fact embedded in a much larger matrix of technologies. Using C# requires using the .NET Framework, including the Common Language Runtime (CLR) and the .NET Framework class library. Similarly, using Java requires using a Java virtual machine and some set of Java packages. The choice implies an enterprise vendor decision as well: C# means Microsoft (today, at least), whereas Java means IBM or BEA or some other non-Microsoft choice. Deciding which of these paths to take based solely on the language is like buying a car because you like the radio. You can do it, but you'll be happier if you choose based on the whole package.
• Isn't C# just a copy of Java? In some ways, yes. The semantics of the CLR are
quite Java-esque, and so any CLR-based language will have a good deal in common with Java. Creating a language that expresses those semantics in a syntax derived from C++ (for example, C#) is bound to result in something that looks a good deal like Java. Yet there are important features in C# that don't exist in Java. One good example is support for attributes, which allow a developer to easily control significant parts of her code's behavior. In .NET, attributes can be used to control which methods are exposed as SOAP-callable Web services, to set transaction requirements, and more. Still, if Microsoft had been free to make some changes to Java, my guess is that C# wouldn't exist today.
• Isn't C# the native language of .NET? Every language built on the .NET
Framework must use the CLR. The CLR defines core language semantics, and so all of the languages built on it tend to have a great deal in common. The biggest choice a .NET compiler writer has is the syntax his language will use. Microsoft needed to provide a natural path to the .NET Framework for both C++ and Visual Basic developers, and so the company created C# and Visual Basic.NET. Yet the facilities these two languages offer are nearly identical—C# can do just a little bit more—and so neither is the "native" .NET language. There is no such thing. • But won't most .NET developers eventually choose C# over Visual
Basic.NET? No. Because the power of the two languages is so similar, the
primary factor for developers migrating to the .NET world will probably be the syntax they prefer. Since many more developers use Visual Basic today than C++,
I expect that VB.NET will be the most popular choice. For the vast majority of VB developers who are fond of VB-style syntax, there's no reason to switch to C#. I believe that the dominant language for building Windows applications five years from now will still be Visual Basic.
• Will we eventually see a .NET Framework-based version of Java as a competitor to C#? Apparently not. Microsoft will never offer a complete Java
environment because Sun has essentially required that Java licensees implement all of Java—something Microsoft will never do. (Why should it? Does anyone expect Sun to implement C#, VB.NET, and the .NET Framework?) And if a Java aficionado chooses to use a CLR-based Java compiler, such as the one included with Microsoft's JUMP for .NET technology, she's unlikely to be truly happy. Java implies a series of Java libraries and interfaces, such as Swing and Enterprise JavaBeans. The .NET Framework provides its own equivalent technologies, and so most of these won't be available. As a result, a developer using the Java language on the .NET Framework won't feel like she's working in a true Java environment because the familiar libraries won't be there.
C# is probably the most important new programming language since the advent of Java, and it will be used by many developers. But it may have gotten more attention than it deserves, if only because focusing on this new language tends to obscure the many other important innovations in the .NET Framework. Take it seriously, but don't think it's the main event in the new world of .NET.
C# Interview Questions
This is a list of questions I have gathered from other sources and created myself over a period of time from my experience, many of which I felt where incomplete or simply wrong. I have finally taken the time to go through each question and correct them to the best of my ability. However, please feel free to post feedback to challenge, improve, or suggest new questions. I want to thank those of you that have contributed quality questions and corrections thus far.
There are some question in this list that I do not consider to be good questions for an interview. However, they do exist on other lists available on the Internet so I felt compelled to keep them easy access.
General Questions
1. Does C# support multiple-inheritance? No.
2. Who is a protected class-level variable available to? It is available to any sub-class (a class inheriting this class).
3. Are private class-level variables inherited?
Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited.
4. Describe the accessibility modifier “protected internal”.
It is available to classes that are within the same assembly and derived from the specified base class.
5. What’s the top .NET class that everything is derived from? System.Object.
6. What does the term immutable mean?
The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.
7. What’s the difference between System.String and System.Text.StringBuilder
classes?
System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
8. What’s the advantage of using System.Text.StringBuilder over
System.String?
StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.
9. Can you store multiple data types in System.Array? No.
10. What’s the difference between the System.Array.CopyTo() and
System.Array.Clone()?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.
11. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods.
12. What’s the .NET collection class that allows an element to be accessed using
HashTable.
13. What class is underneath the SortedList class? A sorted HashTable.
14. Will the finally block get executed if an exception has not occurred? Yes.
15. What’s the C# syntax to catch any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.
16. Can multiple catch blocks be executed for a single try statement?
No. Once the proper catch block processed, control is transferred to the finally block (if there are any).
17. Explain the three services model commonly know as a three-tier application. Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).
Class Questions
1. What is the syntax to inherit from a class in C#? Place a colon and then the name of the base class. Example: class MyNewClass : MyBaseClass
2. Can you prevent your class from being inherited by another class? Yes. The keyword “sealed” will prevent the class from being inherited.
3. Can you allow a class to be inherited, but prevent the method from being
over-ridden?
Yes. Just leave the class public and make the method sealed.
4. What’s an abstract class?
A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation.
5. When do you absolutely have to declare a class as abstract?
1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
2. When at least one of the methods in the class is abstract.
6. What is an interface class?
classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.
7. Why can’t you specify the accessibility modifier for methods inside the
interface?
They all must be public, and are therefore public by default.
8. Can you inherit multiple interfaces? Yes. .NET does support multiple interfaces.
9. What happens if you inherit multiple interfaces and they have conflicting
method names?
It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.
To Do: Investigate
10. What’s the difference between an interface and abstract class?
In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface class, no
accessibility modifiers are allowed. An abstract class may have accessibility modifiers.
11. What is the difference between a Struct and a Class?
Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that structs cannot inherit.
Method and Property Questions
1. What’s the implicit name of the parameter that gets passed into the set
method/property of a class?
Value. The data type of the value parameter is defined by whatever data type the property is declared as.
2. What does the keyword “virtual” declare for a method or property? The method or property can be overridden.
3. How is method overriding different from method overloading?
When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class.
4. Can you declare an override method to be static if the original method is not
No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override)
5. What are the different ways a method can be overloaded?
Different parameter data types, different number of parameters, different order of parameters.
6. If a base class has a number of overloaded constructors, and an inheriting
class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.
Events and Delegates
1. What’s a delegate?
A delegate object encapsulates a reference to a method.
2. What’s a multicast delegate?
A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.
XML Documentation Questions
1. Is XML case-sensitive? Yes.
2. What’s the difference between // comments, /* */ comments and ///
comments?
Single-line comments, multi-line comments, and XML documentation comments.
3. How do you generate documentation from the C# file commented properly
with a command-line compiler?
Compile it with the /doc switch.
Debugging and Testing Questions
1. What debugging tools come with the .NET SDK?
1. CorDBG – command-line debugger. To use CorDbg, you must compile the original C# file using the /debug switch.
2. DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR.
2. What does assert() method do?
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
3. What’s the difference between the Debug class and Trace class?
Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
4. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose. For applications that are constantly running you run the risk of overloading the machine and the hard drive. Five levels range from None to Verbose, allowing you to fine-tune the tracing activities.
5. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor.
6. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger.
7. What are three test cases you should go through in unit testing? 1. Positive test cases (correct data, correct output).
2. Negative test cases (broken or missing data, proper handling). 3. Exception test cases (exceptions are thrown and caught properly).
8. Can you change the value of a variable while debugging a C# application? Yes. If you are debugging via Visual Studio.NET, just go to Immediate window.
ADO.NET and Database Questions
1. What is the role of the DataReader class in ADO.NET connections?
It returns a read-only, forward-only rowset from the data source. A DataReader provides fast access when a forward-only sequential read is needed.
2. What are advantages and disadvantages of Microsoft-provided data provider
classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a
.NET layer on top of the OLE layer, so it’s not as fastest and efficient as SqlServer.NET.
3. What is the wildcard character in SQL?
Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.
4. Explain ACID rule of thumb for transactions. A transaction must be:
1. Atomic - it is one unit of work and does not dependent on previous and following transactions.
2. Consistent - data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t.
3. Isolated - no transaction sees the intermediate results of the current transaction).
4. Durable - the values persist if the data had been committed even if the system crashes right after.
5. What connections does Microsoft SQL Server support?
Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password).
6. Between Windows Authentication and SQL Server Authentication, which
one is trusted and which one is untrusted?
Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.
7. What does the Initial Catalog parameter define in the connection string? The database name to connect to.
8. What does the Dispose method do with the connection object? Deletes it from the memory.
To Do: answer better. The current answer is not entirely correct.
9. What is a pre-requisite for connection pooling?
Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings. The connection string must be identical.
Assembly Questions
1. How is the DLL Hell problem solved in .NET?
to run (which was available under Win32), but also the version of the assembly.
2. What are the ways to deploy an assembly?
An MSI installer, a CAB archive, and XCOPY command.
3. What is a satellite assembly?
When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
4. What namespaces are necessary to create a localized application? System.Globalization and System.Resources.
5. What is the smallest unit of execution in .NET? an Assembly.
6. When should you call the garbage collector in .NET?
As a good rule, you should not call the garbage collector. However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. However, this is usually not a good practice.
7. How do you convert a value-type to a reference-type? Use Boxing.
8. What happens in memory when you Box and Unbox a value-type?
Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack.
Written by Riley Perry from Distributed Development OK – here we go, the answers to the first 173.
1. Name 10 C# keywords.
abstract, event, new, struct, explicit, null, base, extern, object, this
2. What is public accessibility? There are no access restrictions.
Access is restricted to types derived from the containing class.
4. What is internal accessibility?
A member marked internal is only accessible from files within the same assembly.
5. What is protected internal accessibility?
Access is restricted to types derived from the containing class or from files within the same assembly.
6. What is private accessibility?
Access is restricted to within the containing class.
7. What is the default accessibility for a class? internal for a top level class, private for a nested one.
8. What is the default accessibility for members of an interface? public
9. What is the default accessibility for members of a struct? private
10.Can the members of an interface be private?
No.
11.Methods must declare a return type, what is the keyword used when nothing is returned from the method?
void
12.Class methods to should be marked with what keyword?
static
13.Write some code using interfaces, virtual methods, and an abstract class.
publicinterface Iexample1 {
int MyMethod1(); }
publicinterface Iexample2 {
int MyMethod2(); }
publicabstractclass ABSExample : Iexample1, Iexample2 {
public ABSExample() {
System.Console.WriteLine("ABSExample constructor"); }
publicint MyMethod1() {
return 1; }
publicint MyMethod2() {
return 2; }
}
publicclass VIRTExample : ABSExample {
public VIRTExample() {
System.Console.WriteLine("VIRTExample constructor"); }
publicoverride void MyABSMethod() {
System.Console.WriteLine("Abstract method made concrete"); }
publicvirtual void VIRTMethod1() {
System.Console.WriteLine("VIRTMethod1 has NOT been overridden");
}
publicvirtual void VIRTMethod2() {
System.Console.WriteLine("VIRTMethod2 has NOT been overridden");
} }
publicclass FinalClass : VIRTExample {
publicoverride void VIRTMethod2() {
System.Console.WriteLine("VIRTMethod2 has been overridden"); }
14.A class can have many mains, how does this work?
Only one of them is run, that is the one marked (public) static, e.g:
publicstaticvoid Main(string[] args) {
//
// TODO: Add code to start application here //
}
privatevoid Main(string[] args, int i) {
}
15.Does an object need to be made to run main?
No
16.Write a hello world console application.
using System;
namespace Console1 {
class Class1 {
[STAThread] // No longer needed staticvoid Main(string[] args) {
Console.WriteLine("Hello world"); }
} }
17.What are the two return types for main?
void and int
18.What is a reference parameter?
Reference parameters reference the original object whereas value parameters make a local copy and do not affect the original. Some example code is shown:
using System;
namespace Console1 {
class Class1 {
staticvoid Main(string[] args) {
TestRef tr1 = new TestRef(); TestRef tr2 = new TestRef();
tr1.TestValue = "Original value"; tr2.TestValue = "Original value"; int tv1 = 1;
int tv2 = 1;
Console.WriteLine(tv1); Console.WriteLine(tv2); Console.WriteLine(tr1.TestValue); Console.WriteLine(tr2.TestValue); Console.ReadLine(); }
staticpublicvoid TestRefVal(refint tv1Parm, int tv2Parm,
ref TestRef tr1Parm, TestRef tr2Parm) {
tv1Parm = 2; tv2Parm = 2;
tr1Parm.TestValue = "New value"; tr2Parm.TestValue = "New value"; }
} }
class TestRef {
publicstring TestValue; }
2 1
New value New value
19.What is an out parameter?
An out parameter allows an instance of a parameter object to be made inside a method. Reference parameters must be initialised but out gives a reference to an uninstanciated object.
20.Write code to show how a method can accept a varying number of parameters. using System; namespace Console1 { class Class1 {
staticvoid Main(string[] args) {
ParamsMethod(1,"example"); ParamsMethod(1,2,3,4); Console.ReadLine(); }
staticvoid ParamsMethod(paramsobject[] list) {
foreach (object o in list) {
Console.WriteLine(o.ToString()); }
} }
}
21.What is an overloaded method?
An overloaded method has multiple signatures that are different. 22.What is recursion?
Recursion is when a method calls itself. 23.What is a constructor?
A constructor performs initialisation for an object (including the struct type) or class.
24.If I have a constructor with a parameter, do I need to explicitly create a default constructor?
Yes
25.What is a destructor?
A C# destuctor is not like a C++ destructor. It is actually an override for Finalize(). This is called when the garbage collector discovers that the object is
unreachable. Finalize() is called before any memory is reclaimed. 26.Can you use access modifiers with destructors?
No
27.What is a delegate?
A delegate in C# is like a function pointer in C or C++. A delegate is a variable that calls a method indirectly, without knowing its name. Delegates can point to static or/and member functions. It is also possible to use a multicast delegate to point to multiple functions.
Member function with a parameter using System; namespace Console1 { class Class1 {
delegatevoid myDelegate(int parameter1); staticvoid Main(string[] args)
{
MyClass myInstance = new MyClass();
myDelegate d = new myDelegate(myInstance.AMethod);
d(1); // <--- Calling function without knowing its name.
Test2(d);
Console.ReadLine(); }
staticvoid Test2(myDelegate d) {
d(2); // <--- Calling function without knowing its name. }
class MyClass {
publicvoid AMethod(int param1) {
Console.WriteLine(param1); }
} }
Multicast delegate calling static and member functions
using System;
namespace Console1 {
class Class1 {
delegatevoid myDelegate(int parameter1); staticvoid AStaticMethod(int param1) {
Console.WriteLine(param1); }
staticvoid Main(string[] args) {
MyClass myInstance = new MyClass();
myDelegate d = null;
d += new myDelegate(myInstance.AMethod); d += new myDelegate(AStaticMethod);
d(1); //both functions will be run. Console.ReadLine();
} }
class MyClass {
publicvoid AMethod(int param1) {
Console.WriteLine(param1); }
} }
29.What is a delegate useful for?
The main reason we use delegates is for use in event driven programming. 30.What is an event?
See 32
31.Are events synchronous of asynchronous?
Asynchronous
32.Events use a publisher/subscriber model. What is that?
Objects publish events to which other applications subscribe. When the publisher raises an event all subscribers to that event are notified.
33.Can a subscriber subscribe to more than one publisher?
Yes, also - here's some code for a publisher with multiple subscribers.
using System;
namespace Console1 {
class Class1 {
delegatevoid myDelegate(int parameter1); staticevent myDelegate myEvent;
staticvoid AStaticMethod(int param1) {
Console.WriteLine(param1); }
staticvoid Main(string[] args) {
MyClass myInstance = new MyClass();
myEvent += new myDelegate(myInstance.AMethod); myEvent += new myDelegate(AStaticMethod);
myEvent(1); //both functions will be run. Console.ReadLine();
}
class MyClass {
publicvoid AMethod(int param1) { Console.WriteLine(param1); } } } Another example: using System; using System.Threading; namespace EventExample {
publicclass Clock {
publicdelegatevoid TwoSecondsPassedHandler(object
clockInstance, TimeEventArgs time);
//The clock publishes an event that others subscribe to
publicevent TwoSecondsPassedHandler TwoSecondsPassed;
publicvoid Start() {
{
Thread.Sleep(2000);
//Raise event
TwoSecondsPassed(this, new TimeEventArgs(1)); }
} }
publicclass TimeEventArgs : EventArgs {
public TimeEventArgs(int second) {
seconds += second;
instanceSeconds = seconds; }
privatestaticint seconds; publicint instanceSeconds; }
publicclass MainClass {
staticvoid Main(string[] args) {
// add some subscribers cl.TwoSecondsPassed += new Clock.TwoSecondsPassedHandler(Subscriber1); cl.TwoSecondsPassed += new Clock.TwoSecondsPassedHandler(Subscriber2); cl.Start(); Console.ReadLine(); }
publicstaticvoid Subscriber1(object clockInstance, TimeEventArgs time)
{
Console.WriteLine("Subscriber1:" + time.instanceSeconds); }
publicstaticvoid Subscriber2(object clockInstance, TimeEventArgs time) { Console.WriteLine("Subscriber2:" + time.instanceSeconds); } } }
34.What is a value type and a reference type?
A reference type is known by a reference to a memory location on the heap. A value type is directly stored in a memory location on the stack. A reference type is essentially a pointer, dereferencing the pointer takes more time than directly accessing the direct memory location of a value type.
Bool, char, int, byte, double
36.string is an alias for what?
System.String
37.Is string Unicode, ASCII, or something else?
Unicode
38.Strings are immutable, what does this mean? Any changes to that string are in fact copies.
39.Name a few string properties.
trim, tolower, toupper, concat, copy, insert, equals, compare. 40.What is boxing and unboxing?
Converting a value type (stack->heap) to a reference type (heap->stack), and vise-versa.
41.Write some code to box and unbox a value type.
// Boxing
int i = 4;
object o = i; // Unboxing i = (int) o;
42.What is a heap and a stack?
There are 2 kinds of heap – 1: a chunk of memory where data is stored and 2: a tree based data structure. When we talk about the heap and the stack we mean the first kind of heap. The stack is a LIFO data structure that stores variables and flow control information. Typically each thread will have its own stack. 43.What is a pointer?
44.What does new do in terms of objects? Initializes an object.
45.How do you dereference an object? Set it equal to null.
46.In terms of references, how do == and != (not overridden) work? They check to see if the references both point to the same object.
47.What is a struct?
Unlike in C++ a struct is not a class – it is a value type with certain restrictions. It is usually best to use a struct to represent simple entities with a few variables. Like a Point for example which contains variables x and y.
48. Describe 5 numeric value types ranges.
sbyte -128 to 127, byte 0 – 255, short -32,768 to 32,767, int -2,147,483,648 to 2,147,483,647, ulong 0 to 18,446,744,073,709,551,615
49.What is the default value for a bool?
false
50.Write code for an enumeration.
publicenum animals {Dog=1,Cat,Bear}; 51.Write code for a case statement.
switch (n) { case 1: x=1; break; case 2: x=2;
break; default:
gotocase 1; }
52.Is a struct stored on the heap or stack?
Stack
53.Can a struct have methods?
Yes
54.What is checked { } and unchecked { }?
By default C# does not check for overflow (unless using constants), we can use checked to raise an exception. E.g.:
staticshort x = 32767; // Max short value
staticshort y = 32767;
// Using a checked expression
publicstaticint myMethodCh() {
int z = 0; try
{
z = checked((short)(x + y)); //z = (short)(x + y);
}
catch (System.OverflowException e) {
System.Console.WriteLine(e.ToString()); }
return z; // Throws the exception OverflowException }
This code will raise an exception, if we remove unchecked as in: //z = checked((short)(x + y));
z = (short)(x + y);
Then the cast will raise no overflow exception and z will be assigned –2. unchecked can be used in the opposite way, to say avoid compile time errors with constanst overflow. E.g. the following will cause a compiler error:
constshort x = 32767; // Max short value
constshort y = 32767;
publicstaticint myMethodUnch() {
int z = (short)(x + y); return z; // Returns -2 }
The following will not:
constshort x = 32767; // Max short value
constshort y = 32767;
publicstaticint myMethodUnch() {
int z = unchecked((short)(x + y)); return z; // Returns -2
}
55.Can C# have global overflow checking?
Yes
56.What is explicit vs. implicit conversion?
When converting from a smaller numeric type into a larger one the cast is implicit. An example of when an explicit cast is needed is when a value may be truncated.
57.Give examples of both of the above.
// Implicit
short shrt = 400;
int intgr = shrt; // Explicit
shrt = (short) intgr;
58.Can assignment operators be overloaded directly?
No
59.What do operators is and as do?
as acts is like a cast but returns a null on conversion failure. Is compares an object to a type and returns a boolean.
60.What is the difference between the new operator and modifier?
The new operator creates an instance of a class whereas the new modifier is used to declare a method with the same name as a method in one of the parent classes.
61.Explain sizeof and typeof.
typeof obtains the System.Type object for a type and sizeof obtains the size of a type.
Allocate a block of memory on the stack (used in unsafe mode). 63.Contrast ++count vs. count++.
Some operators have temporal properties depending on their placement. E.g.
double x; x = 2; Console.Write(++x); x = 2; Console.Write(x++); Console.Write(x); Returns 323
64.What are the names of the three types of operators? Unary, binary, and conversion.
65.An operator declaration must include a public and static modifier, can it have other modifiers?
No
66.Can operator parameters be reference parameters?
No
67.Describe an operator from each of these categories: Arithmetic: +
Logical (boolean and bitwise): & String concatenation: + Increment, decrement: ++ Shift: >> Relational: == Assignment: = Member access: .
Indexing: [] Cast: ()
Conditional: ?:
Delegate concatenation and removal: + Object creation: new
Type information: as
Overflow exception control: checked Indirection and Address: *
68.What does operator order of precedence mean?
Certain operators are evaluated before others. Brackets help to avoid confusion. 69.What is special about the declaration of relational operators?
Relational operators must be declared in pairs. 70.Write some code to overload an operator.
class TempleCompare {
publicint templeCompareID; publicint templeValue;
publicstatic booloperator == (TempleCompare x, TempleCompare y) {
return (x.templeValue == y.templeValue); }
publicstatic booloperator != (TempleCompare x, TempleCompare y) {
return !(x == y); }
publicoverride bool Equals(object o) {
// check types match
if (o == null || GetType()!= o.GetType()) returnfalse; TempleCompare t = (templeCompare) o;
return (this.templeCompareID == t.templeCompareID) && (this.templeValue == t.templeValue);
}
publicoverride int GetHashCode() { return templeCompareID; } }
71.What operators cannot be overloaded?
=, ., ?:, ->, new, is, sizeof, typeof
72.What is an exception? A runtime error.
73.Can C# have multiple catch blocks?
Yes
74.Can break exit a finally block?
No
75.Can Continue exit a finally block?
No
76.Write some try…catch…finally code.
// try-catch-finally
using System;
publicclass TCFClass {
publicstatic void Main () {
try
{
}
catch(NullReferenceException e) {
Console.WriteLine("{0} exception 1.", e); } catch { Console.WriteLine("exception 2."); } finally { Console.WriteLine("finally block."); } } }
77.What are expression and declaration statements?
• Expression – produces a value e.g. blah = 0
• Declaration – e.g. int blah;
78.A block contains a statement list {s1;s2;} what is an empty statement list?
{;}
79.Write some if… else if… code.
int n=4;
Console.WriteLine("n=1"); elseif (n==2) Console.WriteLine("n=2"); elseif (n==3) Console.WriteLine("n=3"); else Console.WriteLine("n>3"); 80.What is a dangling else?
if (n>0)
if (n2>0)
Console.Write("Dangling Else")
else
81.Is switch case sensitive?
Yes
82.Write some code for a for loop
for (int i = 1; i <= 5; i++) Console.WriteLine(i);
83.Can you increment multiple variables in a for loop control?
Yes – e.g. for (int i = 1; j = 2;i <= 5 ;i++ ;j=j+2) 84.Write some code for a while loop.
int n = 1;
while (n < 6) {
Console.WriteLine("Current value of n is {0}", n); n++;
}
85.Write some code for do… while.
int x; int y = 0; do { x = y++; Console.WriteLine(x); } while(y < 5);
86.Write some code that declares an array on ints, assigns the values: 0,1,2,5,7,8,11 to that array and use a foreach to do something with those values.
int x = 0, y = 0;
int[] arr = newint [] {0,1,2};
foreach (int i in arr) { if (i%2 == 0) x++; else y++; }
87.Write some code for a custom collection class.
using System;
using System.Collections;
publicclass Items : IEnumerable {
private string[] contents; public Items(string[] contents) {
this.contents = contents; }
public IEnumerator GetEnumerator() {
returnnew ItemsEnumerator(this); }
private class ItemsEnumerator : IEnumerator {
privateint location = -1; private Items i;
public ItemsEnumerator(Items i) {
this.i = i; }
{ if (location < i.contents.Length - 1) { location++; returntrue; } else { returnfalse; } }
publicvoid Reset() {
location = -1; }
publicobject Current { get { return i.contents[location]; } } }
static void Main() {
// Test
string[] myArray = {"a","b","c"}; Items items = new Items(myArray); foreach (string item in items)
{ Console.WriteLine(item); } Console.ReadLine(); } }
88.Describe Jump statements: break, continue, and goto.
Break terminates a loop or switch. Continue jumps to the next iteration of an enclosing iteration statement. Goto jumps to a labelled statement.
89.How do you declare a constant?
publicconstint c1 = 5;
90.What is the default index of an array?
0
91.What is array rank? The dimension of the array.
92.Can you resize an array at runtime?
No
No
94.Write some code to implement a multidimensional array.
int[,] b = {{0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9}};
95.Write some code to implement a jagged array.
// Declare the array of two elements:
int[][] myArray = newint[2][];
// Initialize the elements: myArray[0] = newint[5] {1,3,5,7,9}; myArray[1] = newint[4] {2,4,6,8}; 96.What is an ArrayList?
A data structure from System.Collections that can resize itself. 97.Can an ArrayList be ReadOnly?
Yes
98.Write some code that uses an ArrayList. ArrayList list = new ArrayList();
list.Add("Hello"); list.Add("World");
99.Write some code to implement an indexer.
using System;
namespace Console1 {
class Class1 {
staticvoid Main(string[] args) {
MyIndexableClass m = new MyIndexableClass(); Console.WriteLine(m[0]); Console.WriteLine(m[1]); Console.WriteLine(m[2]); Console.ReadLine(); } } class MyIndexableClass {
privatestring []myData = {"one","two","three"}; publicstringthis [int i]
{ get { return myData[i]; } set { myData[i] = value; } }
} }
100. Can properties have an access modifier? Yes
101. Can properties hide base class members of the same name? Yes
102. What happens if you make a property static?
They become class properties.
103. Can a property be a ref or out parameter?
A property is not classified as a variable – it can’t be ref or out parameter. 104. Write some code to declare and use properties.
// instance
publicstring InstancePr { get { return a; } set { a = value; } }
//read-only static
publicstaticint ClassPr { get { return b; } } 105. What is an accessor?
An accessor contains executable statements associated with getting or setting properties.
106. Can an interface have properties? Yes
107. What is early and late binding?
Late binding is using System.object instead of explicitly declaring a class (which is early binding).
108. What is polymorphism
Polymorphism is the ability to implement the same operation many times. Each derived method implements the operation inherited from the base class in its own way.
109. What is a nested class?
A class declare within a class. 110. What is a namespace?
A namespace declares a scope which is useful for organizing code and to distinguish one type from another.
Yes
112. Can base constructors can be private? Yes
113. object is an alias for what? System.Object
114. What is reflection?
Reflection allows us to analyze an assembly’s metadata and it gives us a mechanism to do late binding.
115. What namespace would you use for reflection? System.Reflection
116. What does this do? Public Foo() : this(12, 0, 0)
Calls another constructor in the list
117. Do local values get garbage collected?
They die when they are pulled off the stack (go out of scope). 118. Is object destruction deterministic?
No
119. Describe garbage collection (in simple terms).
Garbage collection eliminates uneeded objects.
1. the new statement allocates memory for an object on the heap.
2. When no objects reference the object it may be removed from the heap (this is a non deterministic process).
3. Finalize is called just before the memory is released.
120. What is the using statement for?
The using statement defines a scope at the end of which an object will be disposed.
To refer to a member in the base class use:return base.NameOfMethod(). 122. Can you derive from a struct?
No
123. Does C# supports multiple inheritance? No
124. All classes derive from what?
System.Object
125. Is constructor or destructor inheritance explicit or implicit? What
does this mean?
Constructor or destructor inheritance is explicit…. Public Extended : base() this is called the constructor initializer.
126. Can different assemblies share internal access? No
127. Does C# have “friendship”? Not before C# 2.0
128. Can you inherit from multiple interfaces? Yes
129. In terms of constructors, what is the difference between: public
MyDerived() : base() an public MyDerived() in a child class?
Nothing
130. Can abstract methods override virtual methods? Yes
131. What keyword would you use for scope name clashes? this
Yes
133. What are attributes?
Attributes are declarative tags which can be used to mark certain entities (like methods for example).
134. Name 3 categories of predefined attributes.
COM Interop, Transaction, Visual Designer Component Builder 135. What are the 2 global attributes.
assembly and module.
136. Why would you mark something as Serializable?
To show that the marked type can be serialized.
137. Write code to define and use your own custom attribute.
(From MSDN)
// cs_attributes_retr.cs
using System;
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct, AllowMultiple=true)]
publicclass Author : Attribute {
public Author(string name) {
this.name = name; version = 1.0; }
publicdouble version; string name;
publicstring GetName() {
return name; }
}
138. List some custom attribute scopes and possible targets.
Assembly – assembly Class – type
Delegate - type, return
139. List some compiler directives?
#if #else #elif #endif #define #undef #warning #error #line #region #endregion 140. What is a thread?
A thread is a the entity within a process that Windows schedules for execution. A thread has:
• The contents of a set of CPU registers representing the state of the processor.
• 2 stacks, 1 for the thread to use in kernel mode, and 1 for user mode. • Private storage called Thread Local Storage for use by subsystems,
run-time libraries, and DLLs. • A thread ID.
Threads sometimes have their own security context. 141. Do you spin off or spawn a thread?
Spin off
142. What is the volatile keyword used for?
It indicates a field can be modified by an external entity (thread, OS, etc.). 143. Write code to use threading and the lock keyword.
using System; using System.Threading; namespace ConsoleApplication4 { class Class1 { [STAThread]
staticvoid Main(string[] args) {
ThreadClass tc1 = new ThreadClass(1); ThreadClass tc2 = new ThreadClass(2); Thread oT1 = new Thread(new
ThreadStart(tc1.ThreadMethod));
Thread oT2 = new Thread(new
oT1.Start(); oT2.Start(); Console.ReadLine(); } } class ThreadClass {
privatestaticobject lockValue = "dummy"; publicint threadNumber;
public ThreadClass(int threadNumber) {
this.threadNumber = threadNumber; }
publicvoid ThreadMethod() { for (;;) { lock(lockValue) { Console.WriteLine(threadNumber + " working"); Thread.Sleep(1000); } }
} }
}
144. What is Monitor?
Monitor is a class that has various functions for thread synchronization. 145. What is a semaphore?
A resource management, synchronization, and locking tool.
146. What mechanisms does C# have for the readers, writers problem?
System.Threading.ReaderWriterLock which has methods AcquireReaderLock, ReleaseReaderLock, AcquireWriterLock, and ReleaseWriterLock
147. What is Mutex?
A Mutex object is used to guarantee only one thread can access a critical resource an any one time.
148. What is an assembly?
Assemblies contain logical units of code in MSIL, metadata, and usually a manifest. Assemblies can be signed and the can dome in the form of a DLL or EXE.
149. What is a DLL?
A set of callable functions, which can be dynamically loaded. 150. What is an assembly identity?
Assembly identity is name, version number, and optional culture, and optional public key to guarantee uniqueness.
151. What does the assembly manifest contain?
Assembly manifest lists all names of public types and resources and their locations in the assembly.
Use IDLASM to see assembly internals. It disassembles into MSIL. 153. Where are private assemblies stored?
Same folder as exe
154. Where are shared assemblies stored? The GAC
155. What is DLL hell?
DLLs, VBX or OCX files being unavailable or in the wrong versions. Applicatioins using say these older DLLs expect some behaviour which is not present.
156. In terms of assemblies, what is side-by-side execution? An app can be configured to use different versions of an assembly simultaneously.
157. Name and describe 5 different documentation tags.
///<value></value> ///<example></example>
///<exception cref=""></exception> ///<include file='' path='[@name=""]'/> ///<param name="args"></param> ///<paramref name=""/> ///<permission cref=""></permission> ///<remarks> ///</remarks> ///<summary> /// <c></c> /// <code></code>