C#Interview Questions
Short Description
C# interview question...
Description
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. 9. How’s method overriding different from overloading?
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 nonstatic? 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 overridden? 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 overridden. 17. What’s an interface class?
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 having a mutable string where a variety of operations can be performed.
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 } Tech Interviews comment by Richard Lowe
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 SelfTraining 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 16. Thought I’d offer a few points on your list of questions.
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,oledb,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 Tech Interviews comment by 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 a unique key?
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? Interfaces, like classes, define a set of properties, methods, and events. But unlike
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 static?
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? Assembly versioning allows the application to specify not only the library it needs
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. 3. What is protected accessibility?
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. using System;
public interface Iexample1 { int MyMethod1(); } public interface Iexample2 { int MyMethod2(); } public abstract class ABSExample : Iexample1, Iexample2 { public ABSExample() { System.Console.WriteLine("ABSExample constructor"); } public int MyMethod1() { return 1; } public int MyMethod2() { return 2; } public abstract void MyABSMethod();
} public class VIRTExample : ABSExample { public VIRTExample() { System.Console.WriteLine("VIRTExample constructor"); } public override void MyABSMethod() { System.Console.WriteLine("Abstract method made concrete"); } public virtual void VIRTMethod1() { System.Console.WriteLine("VIRTMethod1 has NOT been overridden"); } public virtual void VIRTMethod2() { System.Console.WriteLine("VIRTMethod2 has NOT been overridden"); } } public class FinalClass : VIRTExample {
public override 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: public static void Main(string[] args) { // // TODO: Add code to start application here // } private void 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 static void 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 { static void 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; TestRefVal(ref tv1, tv2, ref tr1, tr2);
Console.WriteLine(tv1); Console.WriteLine(tv2); Console.WriteLine(tr1.TestValue); Console.WriteLine(tr2.TestValue); Console.ReadLine(); } static public void TestRefVal(ref int tv1Parm, int tv2Parm, ref TestRef tr1Parm, TestRef tr2Parm) { tv1Parm = 2; tv2Parm = 2; tr1Parm.TestValue = "New value"; tr2Parm.TestValue = "New value"; } } } class TestRef { public string TestValue; } The output for this is:
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 { static void Main(string[] args) { ParamsMethod(1,"example"); ParamsMethod(1,2,3,4); Console.ReadLine(); } static void ParamsMethod(params object[] 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. 28. Write some code to use a delegate.
Member function with a parameter using System; namespace Console1 { class Class1 { delegate void myDelegate(int parameter1); static void Main(string[] args) { MyClass myInstance = new MyClass();
myDelegate d = new myDelegate(myInstance.AMethod);
d(1); //
View more...
Comments