Skip to main content

C# interview question answers

Q-1: Which of the following statement is true?
a. try block must be followed by catch and finally block both.
b. try block must be followed by catch or finally block or both.
c. try block cannot include another try block.
d. All of the above.

Correct Answer: (b) try block must be followed by catch or finally block or both.

Q-2: Which of the following datatype can be used with enum?
a. Int
b. String
c. Boolean
4. All of the above

Correct Answer: (a) Int

Q-3: A partial class allows ________
a. Implementation of single class in multiple .cs files.
b. Declaration of multiple classes in a single .cs file.
c. Implementation of multiple interfaces to single class.
d. Multiple class inheritance.

Correct Answer: (a) Implementation of single class in multiple .cs files.

Q-4: C# class can inherit multiple ________
a. Class
b. Interface
c. Abstract class
d. Static class

Correct Answer: (b) Interface

Q-5: Struct is a _____.
a. Reference type
b. Value type
c. Class type
d. String type

Correct Answer: (b) Value type

Q-6: Which of the following is true for ReadOnly variables?
a. Value will be assigned at runtime.
b. Value will be assigned at compile time.
c. Value will be assigned when it accessed first time
d. None of the above

Correct Answer: (a) Value will be assigned at runtime.

Q-7: LINQ stands for ________.
a. Language Integrated Query
b. Local Integration Query
c. Language Included Query
d. Lazy Integrated Query

Correct Answer: (a) Language Integrated Query

Q-8: Which of the following is true for dynamic type in C#?
a. It allows multiple time declaration of a variable.
b. It allows compile time type checking
c. It escapes compile time type checking
d. None of the above.

Correct Answer: (c) It escapes compile time type checking

Q-9: String data type is ______.
a. Mutable
b. Immutable
c. Static
d. Value type

Correct Answer: (b) Immutable

Q-10: Which of the following is right way of declaring an array?
a. Int[] intArray = new int[];
b. Int intArray[] = new int[5];
c. Int[] intArray = new int[5];
d. Int[] intArray = new int[]{1, 2, 3, 4, 5};

Correct Answer: (c) Int[] intArray = new int[5];

Q-11: What is Nullable type?
a. It allows assignment of null to reference type.
b. It allows assignment of null to value type.
c. It allows assignment of null to static class.
d. None of the above.

Correct Answer: (b) It allows assignment of null to value type.

Q-12: Which of the following is a reference type in C#?
a. String
b. Long
c. Boolean
d. None of the above

Correct Answer: (a) String

Q-13: Data type of a variable declared using var will be assigned at _______.
a. Runtime
b. Compile time
c. CLR time
d. Application Initialization time.

Correct Answer: (b) Compile time

Q-14: 10 > 9 ? “10 is greater than 9” : “9 is greater than 10” is an example of _______
a. Ternary operator
b. Conditional operator
c. Greater than operator
d. Inverse operator

Correct Answer: (a) Ternary operator

Q-15: Which of the following statement is true?
a. A finally block may not execute every time
b. A finally block cannot include return or break keyword.
c. A finally block can come before catch block.
d. Multiple finally block is possible.

Correct Answer: (b) A finally block cannot include return or break keyword.

Q-16: What is indexer?
a. It allows an instance of a class to be indexed like an array
b. It allows enumerator with class
c. It creates index for instances of a class.
d. None of the above.

Correct Answer: (a) It allows an instance of a class to be indexed like an array

Q-17: Return type of Predicate <T>() is always a ______.
a. Integer
b. String
c. Boolean
d. Void

Correct Answer: (c) Boolean

Q-18: An array in C# starts with _____ index.
a. One
b. Zero
c. -1
d. None of the above

Correct Answer: (b) Zero

Q-19: Which of the followings are value types in C#?
a. Int32
b. Double
c. Decimal
d. All of the above

Correct Answer: (d) All of the above

Q-20: Func and Action are the types of ______.
a. Utility function
b. Delegate
c. Event
d. Generic class

Correct Answer: (b) Delegate

XmlDocument class

In the previous article we have seen how to write an XML file using XmlWriter class, in this article we will see how to write an XML file using XmlDocument class. Both are writing the XML file only, however when we want to update an existing XML file then XmlDocument class will be easy to use. Because XmlWriter class will use higher memory consumption.

Now look at the below sample code


using System.Xml;

namespace DocumentXml
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument document = new XmlDocument();
            XmlNode rootElement = document.CreateElement("developers");
            document.AppendChild(rootElement);

            XmlNode developerNode = document.CreateElement("developer");
            XmlAttribute noteAttribute = document.CreateAttribute("dept");
            noteAttribute.Value = "DotNet";
            developerNode.Attributes.Append(noteAttribute);
            developerNode.InnerText = "Tarun Dudhatra";
            rootElement.AppendChild(developerNode);

            developerNode = document.CreateElement("developer");
            noteAttribute = document.CreateAttribute("dept");
            noteAttribute.Value = "DotNet";
            developerNode.Attributes.Append(noteAttribute);
            developerNode.InnerText = "Milan Dudhatra";
            rootElement.AppendChild(developerNode);

            document.Save(@"D:\Tarun\developers.xml"); // Change file path here
        }
    }
}

Above code will produce below output


<developers>
  <developer dept="DotNet">Tarun Dudhatra</developer>
  <developer dept="DotNet">Milan Dudhatra</developer>
</developers>

As we can see, first we have created an object of XmlDocument class. It will be used to create new element and new attribute both using the CreateElement() and CreateAttribute() methods. Each time we will do the same process, what I mean here is if we want to create 3 nodes in the root element developers then we will do use document object 3 times to create XmlNode element using the CreateElement(). We append the element to either root element or any other element using .Append() method of the Attributes property. Attributes are appended to the element itself where we want to add in any node. Once all the nodes are created with attributes and appended to the rool element or any other element, the entire XML file is written to the disk using Save() method, which we have write at the last line.

It’s Pretty cool, Isn’t it?

Now download the sample project with code written earlier.

Writing XML with the XmlWriter class

In previous article we have see about writing and reading text document, but now it’s time to start dealing with XML file. Anyhow XML is just a plain text, we can simply start writing an XML tags to the file and save it with .xml file extension. But for .net framework it is very easy and safe to handle.

For writing an XML file .net framework provides two different options.
XMLWriter and XmlDocument, we will see XMLDocument in the next article. In this article we will focus on XMLWriter approach

Let’s see the basic different between XmlWriter and XmlDocument. XMLWriter uses less memory compare to XmlDocument, that is the only 1 issue if we are writing a vey big file. Another difference is if we are modofing an xml file using XmlDocument, we can read an exisitng file, change it as required and update the file while in XMLWriter we need to create the whole document from scratch every time. That’s it, so it is upto user’s preference and situation when which one should be used.

Now lets have a look at the exmple of writing XML file using XmlWriter class.

using System.Xml;

namespace XmlWriterExample
{
    class Developer
    {
        public int Id { get; set; }
        public string FullName { get; set;  }
        public string Department { get; set; }
        public int Salary { get; set; }
    }

    class Program
    {
        static void Main()
        {
            Developer[] developers = new Developer[2];
            developers[0] = new Developer() {Id= 2, FullName="Tarun Dudhatra", Department = ".Net", Salary=50000 };
            developers[1] = new Developer() { Id = 6, FullName = "Milan Dudhatra", Department = ".Net", Salary = 40000 };

            using (XmlWriter fileWriter = XmlWriter.Create(@"D:\Tarun\developer.xml"))
            {
                fileWriter.WriteStartDocument();
                fileWriter.WriteStartElement("developers");

                foreach (Developer developer in developers)
                {
                    fileWriter.WriteStartElement("Developer");

                    fileWriter.WriteElementString("ID", developer.Id.ToString());
                    fileWriter.WriteElementString("FullName", developer.FullName);
                    fileWriter.WriteElementString("Department", developer.Department);
                    fileWriter.WriteElementString("Salary", developer.Salary.ToString());

                    fileWriter.WriteEndElement();
                }

                fileWriter.WriteEndElement();
                fileWriter.WriteEndDocument();
            }
        }
    }
}

The above C sharp code will generate the following XML file:

<?xml version="1.0" encoding="utf-8"?>
<developers>

	<Developer>
		<ID>2</ID>
		<FullName>Tarun Dudhatra</FullName>
		<Department>.Net</Department>
		<Salary>50000</Salary>
	</Developer>
	
	<Developer>
		<ID>6</ID>
		<FullName>Milan Dudhatra</FullName>
		<Department>.Net</Department>
		<Salary>40000</Salary>
	</Developer>
	
</developers>

Here first we have created an instace of the XmlWriter class with one parameter (obviously it a path of xml file, where we want to create a xml file).

We have started xml document with WriteStartDocument() method, and then create an element called “developers” this will be converted to in xml file. After that we have created an another element called “Developer” which will be child element of previously created “developers” element. Now we have created 4 child element called Id, Fullname, Department and Salary using WriteElementString() method. We then close the WriteEndElement() method for Developer node and out side the forloop we call that method again for “developers” node. After writing all the element to root element we will end the document by calling WriteEndDocument() method.

That’s simple it takes to generate an xml file using XmlWriter class. In the next blog post we will see how to write an xml file using XmlDocument class.

 

Download the sample project