You are on page 1of 281

NOTEPADDDDDD

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Last_Notepaad
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void toolStripMenuItem2_Click(object sender, EventArgs e)


{
OpenFileDialog op = new OpenFileDialog();
op.Title = "open";
op.Filter = "Text DOcument(*.txt)|*.txt|All Files(*.*)|*.*";
if (op.ShowDialog() == DialogResult.OK)
richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
this.Text = op.FileName;
}

private void helpToolStripMenuItem_Click(object sender, EventArgs e)


{
MessageBox.Show("All rights are reserved by author", "help",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}

private void newToolStripMenuItem_Click(object sender, EventArgs e)


{
richTextBox1.Clear();
}

private void richTextBox1_TextChanged(object sender, EventArgs e)


{

private void saveToolStripMenuItem_Click(object sender, EventArgs e)


{
SaveFileDialog op = new SaveFileDialog();
op.Title = "Save";
op.Filter = "Text DOcument(*.txt)|*.txt|All Files(*.*)|*.*";
if (op.ShowDialog() == DialogResult.OK)
richTextBox1.SaveFile(op.FileName, RichTextBoxStreamType.PlainText);
this.Text = op.FileName;
}

private void existToolStripMenuItem_Click(object sender, EventArgs e)


{
Close();
}

private void undoToolStripMenuItem_Click(object sender, EventArgs e)


{
richTextBox1.Undo();
}

private void redoToolStripMenuItem_Click(object sender, EventArgs e)


{

richTextBox1.Redo();
}

private void copyToolStripMenuItem_Click(object sender, EventArgs e)


{

richTextBox1.Copy();
}

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)


{

richTextBox1.Paste();
}

private void cutToolStripMenuItem_Click(object sender, EventArgs e)


{

richTextBox1.Cut();
}

private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)


{
richTextBox1.SelectAll();
}

private void dateTimeToolStripMenuItem_Click(object sender, EventArgs e)


{
richTextBox1.Text = System.DateTime.Now.ToString();
}

private void fontToolStripMenuItem_Click(object sender, EventArgs e)


{
FontDialog op = new FontDialog();
if (op.ShowDialog() == DialogResult.OK)
richTextBox1.Font = op.Font;
}

private void colorToolStripMenuItem_Click(object sender, EventArgs e)


{
ColorDialog op = new ColorDialog();
if (op.ShowDialog() == DialogResult.OK)
richTextBox1.ForeColor = op.Color;
}

}
}

////////////////////
calculator
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CalCulator_Last_attempt
{
public partial class Form1 : Form
{
Double resultValue = 0;
string operationPerformed = "";
bool isOperationPerformed = false;
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{

private void button15_Click(object sender, EventArgs e)


{
switch (operationPerformed)
{
case "+":
textBox_Result.Text = (resultValue +
Double.Parse(textBox_Result.Text)).ToString();
break;
case "-":
textBox_Result.Text = (resultValue -
Double.Parse(textBox_Result.Text)).ToString();
break;
case "*":

textBox_Result.Text = (resultValue *
Double.Parse(textBox_Result.Text)).ToString();
break;
case "/":

textBox_Result.Text = (resultValue /
Double.Parse(textBox_Result.Text)).ToString();
break;
default:
break;

}
resultValue = Double.Parse(textBox_Result.Text);
labelCurrentOperation.Text= "";

private void button_click(object sender, EventArgs e)


{
if( (textBox_Result.Text == "0") || (isOperationPerformed))
textBox_Result.Clear();
isOperationPerformed = false;
Button button = (Button)sender;
if (button.Text == ".")
{
if (!textBox_Result.Text.Contains("."))
textBox_Result.Text = textBox_Result.Text + button.Text;

}
else
textBox_Result.Text = textBox_Result.Text + button.Text;
}

private void operator_click(object sender, EventArgs e)


{
Button button = (Button)sender;
if (resultValue != 0)
{
button18.PerformClick();
operationPerformed = button.Text;
labelCurrentOperation.Text = resultValue + " " + operationPerformed;
isOperationPerformed = true;
}

else {

operationPerformed = button.Text;
resultValue = Double.Parse(textBox_Result.Text);
labelCurrentOperation.Text = resultValue + " " + operationPerformed;
isOperationPerformed = true;
}

private void button1_Click(object sender, EventArgs e)


{
textBox_Result.Text = "0";
}

private void button8_Click(object sender, EventArgs e)


{
textBox_Result.Text = "0";
resultValue = 0;
}
}
}
//////////////////
Web browser
WebBrowser Control

WebBrowser control allows developers to build Web browsing capability within Windows Forms
applications. In this article, I will demonstrate how to use the WebBrowser control in a Windows
Forms application using C# and Visual Studio 2010.

In 2001, I published an article Web Browser in C# and VB.NET that showed how to use the
WebBrowser ActiveX control in a Windows Forms 1.0/1.1 application. Well, things have
changed since then.

This article is written using Visual Studio 2010 and Windows Forms 4. If you do not have Visual
Studio 2010, you may use Visual C# 2010 Express which is free to download from the MSDN
website.

Creating a WebBrowser

Create a Windows Forms application using Visual Studio 2010 or Visual C# 2010 Express.

In this application, I am going to add a ToolStrip and WebBrowser control to the form. In my
ToolStrip control, I add a Label, a TextBox, and a few Button controls with a few separators.

By the time we are done with the application, the final user interface will look like Figure 1.
Figure 1

After your Toolbar looks like Figure 1, drag a WebBrowser control from Toolbox to the Form and
resize and dock the control the way you like on the Form. I dock the WebBrowser control at the
bottom of the window.
Figure 2

In the next step, I am going to set default properties of the WebBrowser control.

To do so, right-click on the WebBrowser control, and select Properties. This action launches the
Properties window. Feel free to set any properties you like. The Url property represents the web
page a WebBrowser displays. In Figure 3, I set http://www.c-sharpcorner.com as the default
page to display in the browser.
Figure 3

Navigation

The WebBrowser class in code behind is associated with the WebBrowser control. So when you
drag and drop a WebBrowser control to the Form, a WebBrowser class instance is created in
the code behind.

The Navigate method of the WebBrowser class is used to open a URL in the WebBrowser.

1. webBrowser1.Navigate(new Uri(url));

The following code snippet is code written on the Go button click event handler where I open a
URL in the WebBrowser using the Navigate method.

1. // GO button click event handler.


2.
3. private void GoButton_Click(object sender, EventArgs e)
4. {
5. if (String.IsNullOrEmpty(UrlTextBox.Text) || UrlTextBox.Text.
Equals("about:blank"))
6. {
7. MessageBox.Show("Enter a valid URL.");
8. UrlTextBox.Focus();
9. return;
10. }
11. OpenURLInBrowser(UrlTextBox.Text);
12. }
13.
14. private void OpenURLInBrowser(string url)
15. {
16.
17. if (!url.StartsWith("http://") && !url.StartsWith("https
://"))
18. {
19. url = "http://" + url;
20. }
21.
22. try
23. {
24. webBrowser1.Navigate(new Uri(url));
25. }
26. catch (System.UriFormatException)
27. {
28. return;
29. }
30. }

WebBrowser control also has built-in browser methods to go home, forward, backward, refresh,
save, print and others.

The following code snippet shows how to use GoForeward, GoBack, GoHome, and Refresh
methods.

1. // Home button takes user home


2.
3. private void HomeButton_Click(object sender, EventArgs e)
4. {
5. webBrowser1.GoHome();
6. }
7.
8. // Go back
9. private void BackButton_Click(object sender, EventArgs e)
10. {
11. if (webBrowser1.CanGoBack)
12. webBrowser1.GoBack();
13. }
14.
15. // Next
16.
17. private void NextButton_Click(object sender, EventArgs e)
18. {
19.
20. if (webBrowser1.CanGoForward)
21. webBrowser1.GoForward();
22. }
23.
24. // Refresh
25.
26. private void RefreshButton_Click(object sender, EventArgs e)
27. {
28. webBrowser1.Refresh();
29. }

The ShowSaveAsDialog, ShowPrintDialog, ShowPrintPreviewDialog, and ShowProperties


methods are used to display SaveAs diaog, Print dialog, PrintPreview dialog, and Properties
dialog respectively. The following code snippet shows how to call these methods.

1. // Save button launches SaveAs dialog


2.
3. private void SaveButton_Click(object sender, EventArgs e)
4. {
5. webBrowser1.ShowSaveAsDialog();
6. }
7.
8. // PrintPreview button launches PrintPreview dialog
9.
10. private void PrintPreviewButton_Click(object sender, EventArgs e)

11. {
12. webBrowser1.ShowPrintPreviewDialog();
13. }
14.
15. // Show Print dialog
16.
17.
18. private void PrintButton_Click(object sender, EventArgs e)
19. {
20. webBrowser1.ShowPrintDialog();
21. }
22.
23. // Properties button
24.
25. private void PropertiesButton_Click(object sender, EventArgs
e)
26. {
27. webBrowser1.ShowPropertiesDialog();
28. }

Summary

In this article, I discussed how to use a WebBrowser control in Windows Forms at design-time
as well as run-time. After that, we saw how to use various properties and methods of the
WebBrowser control.

1 / 33
Can you specify accessibility modifier for methods inside an interface?
No
Yes
2 / 33
What is sealed Modifier
Prevents inheritance of a class
Prevents method overloading
Prevents polymorphism
Prevents illegal access to a class

3 / 33
What is the value returned by function compareTo( ) if the invoking string is less than the
string compared?
Zero
A value of less than zero
A value greater than zero
None of the mentioned

4 / 33
What is used in conversion where the conversion is defined between the expression and the
type.
Ctype
directcast
multicast
Cttype
Generics are used to make reusable code classes to
decrease the code redundancy
improve code performance
improve code indentation
improve code documentation

In c#, the attribute’s information for a Class can be retrieved at


Compile time
Runtime
Both

The space required for structure variables is allocated on the stack.


True
False
Depends on environment

Shared Assemblies can be stored in Global Assembly Cache.


True
False
Structs can be inherited?
Yes
No
If a class ‘demo’ had ‘add’ property with getting and set accessors, then which of the
following statements will work correctly?
math.add = 15;
math m = new math(); m.add = 15;
Console.WriteLine(math.add);
None of the mentioned
CLR is the .Net equivalent of _____.
Java Virtual machine
Common Language Runtime
Common Type System
Common Language Specification
Which is the base class in .NET from which all the classes are derived from?
System.Object
System.Objects
Systems.Object
Systems.Objects

13 / 33
Select the two types of threads mentioned in the concept of multithreading?
Foreground
Background
Only foreground
Both foreground and background
14 / 33
The data members of a class by default are?
protected, public
private, public
private
public

15 / 33
Which of the following statements is incorrect about delegate?
Delegates are reference types.
Delegates are object-oriented
Delegates are type-safe.
Only one can be called using a delegate.

16 / 33
Reference is a ___.
Copy of class which leads to memory allocation.
Copy of class that is not initialized.
Pre-defined data type.
Copy of class creating by an existing instance.
17 / 33
Select the method that doesn’t guarantee the garbage collection of an object.
Dispose()
Finalize()
Open()
None of this
18 / 33
The correct way to overload +operator?
public sample operator + (sample a, sample b)
public abstract operator + (sample a, sample b)
public static operator + (sample a, sample b)
All of the mentioned above
19 / 33
Abstract class contains _____.
Abstract methods
Non Abstract methods
Both
None
20 / 33
What is stored in Heap?
int
enum
reference type
long
21 / 33
Choose the wrong statement about properties used in C#.Net?
Each property consists of accessor as getting and set.
A property cannot be either read or write-only.
Properties can be used to store and retrieve values to and from the data members of a class.
Properties are like actual methods that work like data members.

22 / 33
Which of the following keywords is used to refer base class constructor to subclass
constructor?
this
static
base
extend
23 / 33
What is used as inheritance operator in C#?
Comma
Dot
Colon
SemiColon
24 / 33
The default scope for the members of an interface is _____.
private
public
protected
internal
25 / 33
Struct’s data members are ___ by default.
Protected
Public
Private
Default

26 / 33
Select the control which can’t be placed in the toolbox
Custom Control
User control
Server Control
ASP Control
27 / 33
Select the type of exceptions which is NOT used in .Net.
NullReferenceException
OutOfMemoryException
StackOverflowException
StackUnderflowException
28 / 33
Select the operator used to check the compatibility of an object with a given type
"as"operater
"is" operater
"this" operater
"at" operater

29 / 33
Which of the following statements are correct for C# language?
Every derived class does not define its own version of the virtual method.
By default, the access mode for all methods in C# is virtual.
If a derived class, does not define its own version of the virtual method, then the one present
in the base class gets used.
All of the above.
30 / 33
Select the operator which is used for casting of object to a type or a class.
"as" operater
"is" operater
"this" operater
"at" operater
31 / 33
Select the class which is immutable
System.Text.StringBuilder
System.String
System.StringBuilder
System.Text.Builder

32 / 33
Which of the following is incorrect about constructors?
Defining of constructors can be implicit or explicit.
The calling of constructors is explicit.
Implicit constructors can be parameterized or parameterless.
Explicit constructors can be parameterized or parameterless.
33 / 33
The point at which an exception is thrown is called the _____.
Default point
Invoking point
Calling point
Throw point
Test C# Programming Skills

Before you get into a war with the C# programming test, buy a little time to know about
the three most important data types in C#. These are none other than the trio – Object,
Var, and Dynamic types. Let’s check out what draws a distinction among them?

Object

It took birth with C# 1.0. It creates a generic entity that can hold any type. A method can
accept it as an argument and also return the object type. Without casting to an actual
type, you won’t be able to use it. It’s primarily useful when the data type of target entity is
not known.

Var

It’s relatively new and gets introduced with C# 3.0. Though, it too can store any value but
requires initialization during declaration. It is type safe and doesn’t make the compiler to
flag an error at runtime. Neither it supports to pass as a function argument nor can a
function return it. The compiler relaxes it to work without being cast. You can utilize it to
handle any of the anonymous types.

Dynamic

It’s the newest of the C# construct which got its shape with C# 4.0. It stores values in the
same manner as the legacy Var does. It’s not type safe. And the compiler won’t know
anything about the type. There is no need to cast. But you must aware of the properties
and methods the stored type supports. Otherwise, you may get into runtime issues. It is
fit for situations where there are requirements to use concepts like Reflection or Dynamic
languages or COM methods.

So now, you know the essentials of three object-oriented data types of C#. Please go
ahead to the interview questions/answers section.

C# programming test with 15 questions and answers on classes


C# Programming Test

Q-1. Which of the following can be used to define the member of a class
externally?

a) :
b) ::
c) #
d) none of the mentioned
View answer.

Answer. b)

Q-2. Which of the following operator can be used to access the member
function of a class?

a) :
b) ::
c) .
d) #
View answer.

Answer. c)
Q-3. What will be the output of the following code snippet?

using System;

class emp

public string name;

public string address;

public void display()

Console.WriteLine("{0} is in city {1}", name,


address);

class Program

static void Main(string[] args)

emp obj = new emp();

obj.name = "Akshay";

obj.address = "new delhi";

obj.display();

Console.ReadLine();

}
a) Syntax error
b) {0} is in city {1} Akshay new delhi
c) Akshay is in new delhi
d) Akshay is in city new delhi
e) executes successfully and prints nothing
View answer.

Answer. d)

Q-4. Which of the following statements are correct for the given code snippet:

shape obj;

obj = new shape();

a) creates an object of class shape.


b) To create an object of type shape on the heap or stack depending on its size.
c) create a reference obj of the class shape and an object of type shape on the heap.
d) create an object of type shape on the stack.
View answer.

Answer. c)

Programmers Should Also Follow the Below Post.


☛ Check out 15 C# Questions – For, While Loops and If Else Statements.

Q-5. Which of the following gives the correct count of the constructors that a
class can define?

a) 1
b) 2
c) Any number
d) None of the above
View answer.

Answer. c)
Q-6. What will be the output of the following code snippet?

using System;

class sample

public static void first()

Console.WriteLine("first method");

public void second()

first();

Console.WriteLine("second method");

public void second(int i)

Console.WriteLine(i);

second();

class program

public static void Main()

{
sample obj = new sample();

sample.first();

obj.second(10);

a) second method
10
second method
first method
b) first method
10
first method
second method
c) first method
10
d) second method
10
first method.
View answer.

Answer. b)

Q-7. What will be the output of the following code snippet?

using System;

class program

static void Main(string[] args)

int num = 2;

fun1 (ref num);

Console.WriteLine(num);
Console.ReadLine();

static void fun1(ref int num)

num = num * num * num;

a) 8
b) 0
c) 2
d) 16
View answer.

Answer. a)

Q-8. What will be the output of the following code snippet?

using System;

class program

static void Main(string[] args)

int[] arr = new int[] {1 ,2 ,3 ,4 ,5 };

fun1(ref arr);

Console.ReadLine();

static void fun1(ref int[] array)


{

for (int i = 0; i < array.Length; i=i+2)

array[i] = array[i] + 10;

Console.WriteLine(string.Join(",", array));

a) 1 2 3 4 5
b) 11 12 13 14 15
c) 11 2 13 4 15
d) 1 3 5 7 9
View answer.

Answer. c)

Q-9. Which of the following statements correctly tell the differences between ‘=’
and ‘==’ in C#?

a) ‘==’ operator is used to assign values from one variable to another variable
‘=’ operator is used to compare value between two variables
b) ‘=’ operator is used to assign values from one variable to another variable
‘==’ operator is used to compare value between two variables
c) No difference between both operators
d) None of the mentioned
View answer.

Answer. b)

Q-10. What will be the output of the following code snippet?

using System;

class program
{

static void Main(string[] args)

int x = 4 ,b = 2;

x -= b/= x * b;

Console.WriteLine(x + " " + b);

Console.ReadLine();

a) 4 2
b) 0 4
c) 4 0
d) None of the mentioned
View answer.

Answer. c)

Q-11. What will be the output of the following code snippet?

using System;

class program

static void Main(string[] args)

int x = 8;

int b = 16;

int c = 64;
x /= c /= b;

Console.WriteLine(x + " " + b+ " " +c);

Console.ReadLine();

a) 2 16 4
b) 4 8 16
c) 2 4 8
d) 8 16 64
View answer.

Answer. a)

Q-12. What is the correct name of a method which has the same name as that
of class and used to destroy objects?

Note – This method gets called automatically when the application is at the final stage
waiting for the process to terminate.
a) Constructor
b) Finalize()
c) Destructor
d) End
View answer.

Answer. c)

Q-13. What will be the output of the following code snippet?

using System;

class sample

int i;

double k;
public sample (int ii, double kk)

i = ii;

k = kk;

double j = (i) + (k);

Console.WriteLine(j);

~sample()

double j = i - k;

Console.WriteLine(j);

class Program

static void Main(string[] args)

sample s = new sample(9, 2.5);

a) 0 0
b) 11.5 0
c) Compile time error
d) 11.5 6.5
View answer.

Answer. d)

Don’t Miss to Check out this Awesome Post.


☛ 15 C# Interview Questions that Every Beginner Should Read Once.

Q-14. What will be the output of the following code snippet?

using System;

class sum

public int value;

int num1;

int num2;

int num3;

public sum ( int a, int b, int c)

this.num1 = a;

this.num2 = b;

this.num3 = c;

~ sum()

value = this.num1 * this.num2 * this.num3;


Console.WriteLine(value);

class Program

public static void Main(string[] args)

sum s = new sum(4, 5, 9);

a) 0
b) 180
c) Compile time error
d) 18
View answer.

Answer. b)

Q-15. What will be the output of the following code snippet?

using System;

class Program

static void Main(string[] args)

int num = 5;

int square = 0, cube = 0;


Mul (num, ref square, ref cube);

Console.WriteLine(square + " & " +cube);

Console.ReadLine();

static void Mul (int num, ref int square, ref int cube)

square = num * num;

cube = num * num * num;

a) 125 & 25
b) 25 & 125
c) Compile time error
d) 10 & 15
View answer.

Answer. b)

Home
»
C sharp Solved MCQs»c# solved MCQs
»
C# Solved MCQs
C# Solved MCQs
C sharp Solved MCQs,c# solved MCQs
1.
Which of the following are the correct ways to increment the value of variableaby1?
++a++;
a += 1;
a ++ 1;
a = a +1;
a = +1;
A.
1, 3
B.
2, 4
C.
3, 5
D.
4, 5
E.
None of these
Answer:OptionB
Solved MCQs From:http://cs-mcqs.blogspot.com
2.
What will be the output of the C#.NET code snippet given below?
byteb1 =0xF7;byteb2 =0xAB;bytetemp;
temp = (byte)(b1 & b2);
Console.Write (temp +" ");
temp = (byte)(b1^b2);
Console.WriteLine(temp);
A.
163 92
B.
92 163
C.
192 63
D.
01
Answer:OptionA
Solved MCQs From:http://cs-mcqs.blogspot.com

3.
Which of the following is NOT an Arithmetic operator in C#.NET?
A.
**
B.
+
C.
/
D.
%
E.
*
Answer:OptionA
Solved MCQs From:http://cs-mcqs.blogspot.com
4.
Which of the following are NOT Relational operators in C#.NET?
>=
!=
Not
<=
<>=
A.
1, 3
B.
2, 4
C.
3, 5
D.
4, 5
E.
None of these
Answer:OptionC
Solved MCQs From:http://cs-mcqs.blogspot.com
5.
Which of the following is NOT a Bitwise operator in C#.NET?
A.
&
B.
|
C.
<<
D.
^
E.
~
Answer:OptionC
Solved MCQs From:http://cs-mcqs.blogspot.com

6.
Which of the following statements is correct about the C#.NET code snippet given below?
intd;
d = Convert.ToInt32( !(30<20) );
A.
A value0will be assigned tod.
B.
A value1will be assigned tod.
C.
A value-1will be assigned tod.
D.
The code reports an error.
E.
The code snippet will work correctly if!is replaced byNot.
Answer & Explanation
Answer:OptionB
Explanation:

Sample Program:
boolfalseFlag =false;booltrueFlag =true;

Console.WriteLine("{0} converts to {1}.", falseFlag,


Convert.ToInt32(falseFlag));
Console.WriteLine("{0} converts to {1}.", trueFlag,
Convert.ToInt32(trueFlag));
The example displays the following output:

False converts to 0.
True converts to 1.
Solved MCQs From:http://cs-mcqs.blogspot.com
7.
Which of the following is the correct output for the C#.NET code snippet given below?
Console.WriteLine(13 / 2 + " " + 13 % 2);
A.
6.5 1
B.
6.5 0
C.
60
D.
61
E.
6.5 6.5
Answer & Explanation
Answer:OptionD
Solved MCQs From:http://cs-mcqs.blogspot.com
8.
Which of the following statements are correct about the Bitwise&operator used in C#.NET?
The&operator can be used to Invert a bit.
The&operator can be used to put ON a bit.
The&operator can be used to put OFF a bit.
The&operator can be used to check whether a bit is ON.
The&operator can be used to check whether a bit is OFF.
A.
1, 2, 4
B.
2, 3, 5
C.
3, 4
D.
3, 4, 5
E.
None of these
Answer & Explanation
Answer:OptionD
Solved MCQs From:http://cs-mcqs.blogspot.com

9.
Which of the following are Logical operators in C#.NET?
&&
||
!
Xor
%
A.
1, 2, 3
B.
1, 3, 4
C.
2, 4, 5
D.
3, 4, 5
E.
None of these
Answer & Explanation
Answer:OptionA
Solved MCQs From:http://cs-mcqs.blogspot.com
10.
Supposenis a variable of the type Byte and we wish, to check whether its fourth
bit (from right) is ON or OFF. Which of the following statements will
do this correctly?
A.
if((n&16) ==16)
Console.WriteLine("Third bit is ON");
B.
if((n&8) ==8)
Console.WriteLine("Third bit is ON");
C.
if((n !8) ==8)
Console.WriteLine("Third bit is ON");
D.
if((n ^8) ==8)
Console.WriteLine("Third bit is ON");
E.
if((n ~8) ==8)
Console. WriteLine("Third bit is ON");
Answer:OptionB
Explanation:

byte myByte = 153;// In Binary = 10011001byte n = 8;// In Binary = 00001000


(Here 1 is the 4th bit from right)

Now perform logical AND operation (n & myByte)

10011001
00001000
---------
00001000 Here result is other than 0, so evaluated to True.
---------
If the result is true, then we can understand that 4th bit is ON of the given datamyByte.
Solved MCQs From:http://cs-mcqs.blogspot.com
CONSTRUCTORS

1.
Which of the following statements is correct?
A.
A constructor can be used to set default values and limit instantiation.
B.
C# provides a copy constructor.
C.
Destructors are used with classes as well as structures.
D.
A class can have more than one destructor.
Answer:OptionA
Solved MCQs From:http://cs-mcqs.blogspot.com
2.
Which of the following statements is correct about the C#.NET code snippet given below?
namespace IndiabixConsoleApplication
{classSample{publicintfunc()
{return1;
}publicSingle func()
{return2.4f ;
}
}classProgram{staticvoidMain(string[ ] args)
{
Sample s1 =newSample();inti;
i = s1.func();
Single j;
j = s1.func();
}
}
}
A.
func()is a valid overloaded function.
B.
Overloading works only in case of subroutines and not in case of functions.
C.
func()cannot be considered overloaded because: return value cannot be used to distinguish
between two overloaded functions.
D.
The call toi = s1.func()will assign1toi.
E.
The callj = s1.func()will assign2.4toj.
Answer:OptionC
Solved MCQs From:http://cs-mcqs.blogspot.com
3.
Which of the following ways to create an object of theSampleclass given below will work
correctly?
classSample{inti;
Single j;doublek;publicSample (intii, Single jj,doublekk)
{
i = ii;
j = jj;
k = kk;
}
}
A.
Sample s1 = new Sample();
B.
Sample s1 = new Sample(10);
C.
Sample s2 = new Sample(10, 1.2f);
D.
Sample s3 = new Sample(10, 1.2f, 2.4);
E.
Sample s1 = new Sample(, , 2.5);
Answer:OptionD
Solved MCQs From:http://cs-mcqs.blogspot.com
4.
Which of the following statements are correct about static functions?
Static functions can access only static data.
Static functions cannot call instance functions.
It is necessary to initialize static data.
Instance functions can call static functions and access static data.
thisreference is passed to static functions.
A.
1, 2, 4
B.
2, 3, 5
C.
3, 4
D.
4, 5
E.
None of these
Answer:OptionA
Solved MCQs From:http://cs-mcqs.blogspot.com
5.
Which of the following statements is correct about constructors?
A.
If we provide a one-argument constructor then the compiler still provides a zero-argument
constructor.
B.
Static constructors can use optional arguments.
C.
Overloaded constructors cannot use optional arguments.
D.
If we do not provide a constructor, then the compiler provides a zero-argument constructor.
Answer:OptionD
Solved MCQs From:http://cs-mcqs.blogspot.com

6.
Which of the following is the correct way to define the constructor(s) of theSampleclass if we
are to create objects as per the C#.NET code snippet given below?
Sample s1 =newSample();
Sample s2 =newSample(9,5.6f);
A.
publicSample()
{
i =0;
j =0.0f;
}publicSample (intii, Single jj)
{
i = ii;
j = jj;
}
B.
publicSample (Optionalintii =0, Optional Single jj =0.0f)
{
i = ii;
j = jj;
}
C.
publicSample (intii, Single jj)
{
i = ii;
j = jj;
}
D.
Sample s;
E.
s =newSample();
Answer:OptionA
Solved MCQs From:http://cs-mcqs.blogspot.com
7.
In which of the following should the methods of a class differ if they are to be treated as
overloaded methods?
Type of arguments
Return type of methods
Number of arguments
Names of methods
Order of arguments
A.
2, 4
B.
3, 5
C.
1, 3, 5
D.
3, 4, 5
Answer:OptionC
Solved MCQs From:http://cs-mcqs.blogspot.com
8.
Can static procedures access instance data?
A.
Yes
B.
No
Answer:OptionB
Solved MCQs From:http://cs-mcqs.blogspot.com
9.
Which of the following statements are correct about constructors in C#.NET?
Constructors cannot be overloaded.
Constructors always have the name same as the name of the class.
Constructors are never called explicitly.
Constructors never return any value.
Constructors allocate space for the object in memory.
A.
1, 3, 5
B.
2, 3, 4
C.
3, 5
D.
4, 5
E.
None of these
Answer:OptionB
Solved MCQs From:http://cs-mcqs.blogspot.com
10.
How many times can a constructor be called during lifetime of the object?
A.
As many times as we call it.
B.
Only once.
C.
Depends upon a Project Setting made in Visual Studio.NET.
D.
Any number of times before the object gets garbage collected.
E.
Any number of times before the object is deleted.
Answer:OptionB
Solved MCQs From:http://cs-mcqs.blogspot.com
11.
Is it possible to invoke Garbage Collector explicitly?
A.
Yes
B.
No
Answer & Explanation
Answer:OptionA

Solved MCQs From:http://cs-mcqs.blogspot.com


12.
Which of the following statements are correct about the C#.NET code snippet given below?
classSample{staticinti;intj;publicvoidproc1()
{
i =11;
j =22;
}publicstaticvoidproc2()
{
i =1;
j =2;
}staticSample()
{
i =0;
j =0;
}
}
A.
icannot be initialized inproc1().
B.
proc1()can initializeias well asj.
C.
jcan be initialized inproc2().
D.
The constructor can never be declared asstatic.
E.
proc2()can initializeias well asj.
Answer & Explanation
Answer:OptionB

Solved MCQs From:http://cs-mcqs.blogspot.com


13.
Which of the following statements is correct?
A.
There is one garbage collector per program running in memory.
B.
There is one common garbage collector for all programs.
C.
An object is destroyed by the garbage collector when only one reference refers to it.
D.
We have to specifically run the garbage collector after executing Visual Studio.NET.
Answer & Explanation
Answer:OptionB

Solved MCQs From:http://cs-mcqs.blogspot.com


14.
Is it possible for you to prevent an object from being created by using zero argument
constructor?
A.
Yes
B.
No
Answer & Explanation
Answer:OptionA

Solved MCQs From:http://cs-mcqs.blogspot.com


15.
Which of the following statements are correct about static functions?
A.
Static functions are invoked using objects of a class.
B.
Static functions can access static data as well as instance data.
C.
Static functions are outside the class scope.
D.
Static functions are invoked using class.
Answer & Explanation
Answer:OptionD

Solved MCQs From:http://cs-mcqs.blogspot.com


16.
What will be the output of the C#.NET code snippet given below?
namespace IndiabixConsoleApplication
{classSample{staticSample()
{
Console.Write("Sample class ");
}publicstaticvoidBix1()
{
Console.Write("Bix1 method ");
}
}classMyProgram{staticvoidMain(string[ ] args)
{
Sample.Bix1();
}
}
}
A.
Sample class Bix1 method
B.
Bix1 method
C.
Sample class
D.
Bix1 method Sample class
E.
Sample class Sample class
Answer & Explanation
Answer:OptionA

Solved MCQs From:http://cs-mcqs.blogspot.com


17.
Which of the following statements is correct about constructors in C#.NET?
A.
A constructor cannot be declared asprivate.
B.
A constructor cannot be overloaded.
C.
A constructor can be astaticconstructor.
D.
A constructor cannot accessstaticdata.
E.
thisreference is never passed to a constructor.
Answer & Explanation
Answer:OptionC

Solved MCQs From:http://cs-mcqs.blogspot.com


18.
What will be the output of the C#.NET code snippet given below?
namespace IndiabixConsoleApplication
{classSample{publicstaticvoidfun1()
{
Console.WriteLine("Bix1 method");
}publicvoidfun2()
{
fun1();
Console.WriteLine("Bix2 method");
}publicvoidfun2(inti)
{
Console.WriteLine(i);
fun2();
}
}classMyProgram{staticvoidMain(string[ ] args)
{
Sample s =newSample();
Sample.fun1();
s.fun2(123);
}
}
}
A.
Bix1 method
123
Bixl method
Bix2 method
B.
Bix1 method
123
Bix2 method
C.
Bix2 method
123
Bix2 method
Bixl method
D.
Bixl method
123
E.
Bix2 method
123
Bixl method
Answer & Explanation
Answer:OptionA

Solved MCQs From:http://cs-mcqs.blogspot.com

STRINGS

1.
Which of the following statements are true about the C#.NET code snippet given below?
String s1, s2;
s1 = "Hi";
s2 = "Hi";
String objects cannot be created without usingnew.
Only one object will get created.
s1ands2both will refer to the same object.
Two objects will get created, one pointed to bys1and another pointed to bys2.
s1ands2are references to the same object.
A.
1, 2, 4
B.
2, 3, 5
C.
3, 4
D.
2, 5
Answer & Explanation
Answer:OptionB
Solved MCQs From:http://cs-mcqs.blogspot.com
2.
Which of the following will be the correct output for the C#.NET code snippet given below?
String s1 = "ALL MEN ARE CREATED EQUAL";
String s2;
s2 = s1.Substring(12, 3);
Console.WriteLine(s2);
A.
ARE
B.
CRE
C.
CR
D.
REA
E.
CREATED
Answer & Explanation
Answer:OptionB
Solved MCQs From:http://cs-mcqs.blogspot.com
3.
Which of the following statements will correctly copy the contents of one string into another ?
A.
String s1 = "String";
String s2;
s2 = s1;
B.
String s1 = "String" ;
String s2;
s2 = String.Concat(s1, s2);
C.
String s1 = "String";
String s2;
s2 = String.Copy(s1);
D.
String s1 = "String";
String s2;
s2 = s1.Replace();
E.
String s1 = "String";
String s2;
s2 = s2.StringCopy(s1);
Answer & Explanation
Answer:OptionC

Solved MCQs From:http://cs-mcqs.blogspot.com


4.
The string built
using the String class are immutable (unchangeable), whereas, the ones
built- using the StringBuilder class are mutable.
A.
True
B.
False
Answer & Explanation
Answer:OptionA

Solved MCQs From:http://cs-mcqs.blogspot.com


5.
Which of the following will be the correct output for the C#.NET code snippet given below?
String s1 ="Nagpur";
String s2;
s2 = s1.Insert(6,"Mumbai");
Console.WriteLine(s2);
A.
NagpuMumbair
B.
Nagpur Mumbai
C.
Mumbai
D.
Nagpur
E.
NagpurMumbai
Answer & Explanation
Answer:OptionE

Solved MCQs From:http://cs-mcqs.blogspot.com

6.
Ifs1ands2are references to two strings, then which of the following is the correct way to
compare the two references?
A.
s1 is s2
B.
s1 = s2
C.
s1 == s2
D.
strcmp(s1, s2)
E.
s1.Equals(s2)
Answer & Explanation
Answer:OptionE

Solved MCQs From:http://cs-mcqs.blogspot.com


7.
What will be the output of the C#.NET code snippet given below?
namespaceIndiabixConsoleApplication
{classSampleProgram
{staticvoidMain(string[ ] args)
{stringstr="Hello World!";
Console.WriteLine( String.Compare(str,"Hello World?").GetType() );
}
}
}
A.
0
B.
1
C.
String
D.
Hello World?
E.
System.Int32
Answer & Explanation
Answer:OptionE

Solved MCQs From:http://cs-mcqs.blogspot.com


8.
Which of the following snippets are the correct way to convert aSingleinto aString?
Single f = 9.8f;
String s;
s = (String) (f);
Single f = 9.8f;
String s;
s = Convert.ToString(f);
Single f = 9.8f;
String s;
s = f.ToString();
Single f = 9.8f;
String s;
s = Clnt(f);
Single f = 9.8f;
String s;
s = CString(f);
A.
1, 2
B.
2, 3
C.
1, 3, 5
D.
2, 4
Answer & Explanation
Answer:OptionB
Explanation:

Solved MCQs From:http://cs-mcqs.blogspot.com


9.
Which of the following will be the correct output for the C#.NET code snippet given below?
String s1="Kicit";
Console.Write(s1.IndexOf('c') +" ");
Console.Write(s1.Length);
A.
36
B.
25
C.
35
D.
26
E.
37
Answer & Explanation
Answer:OptionB

Solved MCQs From:http://cs-mcqs.blogspot.com


10.
Which of the following is correct way to convert aStringto anint?
String s ="123";inti;
i = (int)s;
String s ="123";inti;
i =int.Parse(s);
String s ="123";inti;
i = Int32.Parse(s);
String s ="123";inti;
i = Convert.ToInt32(s);
String s ="123";inti;
i = CInt(s);
A.
1, 3, 5
B.
2, 4
C.
3, 5
D.
2, 3, 4
Answer & Explanation
Answer:OptionD
Explanation:

Solved MCQs From:http://cs-mcqs.blogspot.com


11.
Which of the following statements about a String is correct?
A.
A String is created on the stack.
B.
Whether a String is created on the stack or the heap depends on the length of the String.
C.
A String is a primitive.
D.
A String can be created by using the statementString s1 = new String;
E.
A String is created on the heap.
Answer & Explanation
Answer:OptionE

Solved MCQs From:http://cs-mcqs.blogspot.com


12.
Which of the following statement is correct about a String in C#.NET?
A.
A String is mutable because it can be modified once it has been created.
B.
Methods of theStringclass can be used to modify the string.
C.
A number CANNOT be represented in the form of a String.
D.
A String has a zero-based index.
E.
TheSystem.Arrayclass is used to represent a string.
Answer & Explanation
Answer:OptionD

Solved MCQs From:http://cs-mcqs.blogspot.com


13.
Which of the following will be the correct output for the C#.NET code snippet given below?
String s1 ="Five Star";
String s2 ="FIVE STAR";intc;
c = s1.CompareTo(s2);
Console.WriteLine(c);
A.
0
B.
1
C.
2
D.
-1
E.
-2
Answer & Explanation
Answer:OptionD

Solved MCQs From:http://cs-mcqs.blogspot.com


14.
Ifs1ands2are references to two strings then which of the following are the
correct ways to find whether the contents of the two strings are equal?
if(s1 = s2)
if(s1 == s2)
intc;
c = s1.CompareTo(s2);
if( strcmp(s1, s2) )
if(s1iss2)
A.
1, 2
B.
2, 3
C.
4, 5
D.
3, 5
Answer & Explanation
Answer:OptionB

Solved MCQs From:http://cs-mcqs.blogspot.com


15.
Which of the following statements are correct about the String Class in C#.NET?
Two strings can be concatenated by using an expression of the forms3 = s1 + s2;
String is a primitive in C#.NET.
A string built usingStringBuilderClass is Mutable.
A string built usingStringClass is Immutable.
Two strings can be concatenated by using an expression of the forms3 = s1&s2;
A.
1, 2, 5
B.
2, 4
C.
1, 3, 4
D.
3, 5
Answer & Explanation
Answer:OptionC

Solved MCQs From:http://cs-mcqs.blogspot.com

16.
Which of the following statements are correct?
String is a value type.
String literals can contain any character literal including escape sequences.
The equality operators are defined to compare the values of string objects as well as
references.
Attempting to access a character that is outside the bounds of the string results in
anIndexOutOfRangeException.
The contents of a string object can be changed after the object is created.
A.
1, 3
B.
3, 5
C.
2, 4
D.
1, 2, 4
Answer & Explanation
Answer:OptionC

Solved MCQs From:http://cs-mcqs.blogspot.com


17.
Which of the following is the correct way to find out the index of the second's'in the string"She
sells sea shells on the sea-shore"?
A.
String str ="She sells sea shells on the sea-shore";inti;
i = str.SecondIndexOf("s");
B.
String str ="She sells sea shells on the sea-shore";inti, j;
i = str.FirstIndexOf("s");
j = str.IndexOf("s", i +1);
C.
String str ="She sells sea shells on the sea-shore";inti, j;
i = str.IndexOf("s");
j = str.IndexOf("s", i +1);
D.
String str ="She sells sea shells on the sea-shore";inti, j;
i = str.LastIndexOf("s");
j = str.IndexOf("s", i -1);
E.
String str ="She sells sea shells on the sea-shore";inti, j;
i = str.IndexOf("S");
j = str.IndexOf("s", i);
Answer & Explanation
Answer:OptionC

Solved MCQs From:http://cs-mcqs.blogspot.com


Share to:
Share
1
Next
Solved Aptitude MCQs-Trains Related
Previous
dot Net Frame Work Solved MCQs
Related Posts

1. The capability of an object in Csharp to take number of different forms and hence display
behaviour as according is known as ___________
a) Encapsulation
b) Polymorphism
c) Abstraction
d) None of the mentioned
View Answer
Answer: b
Explanation: None.

2. What will be the output of the following C# code?

1. public class sample


2. {
3. public static int x = 100;
4. public static int y = 150;
5.
6. }
7. public class newspaper :sample
8. {
9. new public static int x = 1000;
10. static void Main(string[] args)
11. {
12. console.writeline(sample.x + " " + sample.y + " " +
x);
13. }
14. }

a) 100 150 1000


b) 1000 150 1000
c) 100 150 1000
d) 100 150 100
View Answer
Answer: c
Explanation: sample.x = 100
sample.y = 150
variable within scope of main() is x = 1000
Output :
100 150 1000

3. Which of the following keyword is used to change data and behavior of a base class by
replacing a member of the base class with a new derived member?
a) Overloads
b) Overrides
c) new
d) base
View Answer
Answer: c
Explanation: None.

4. Correct way to overload +operator?


a) public sample operator + (sample a, sample b)
b) public abstract operator + (sample a,sample b)
c) public static sample operator + (sample a, sample b)
d) all of the mentioned
View Answer
Answer: d
Explanation: None.
advertisement

5. What will be the Correct statement of the following C# code?

1. public class maths


2. {
3. public int x;
4. public virtual void a()
5. {
6.
7. }
8.
9. }
10. public class subject : maths
11. {
12. new public void a()
13. {
14.
15. }
16.
17. }

a) The subject class version of a() method gets called using sample class reference which
holds subject class object
b) subject class hides a() method of base class
c) The code replaces the subject class version of a() with its math class version
d) None of the mentioned
View Answer
Answer: d
Explanation: None.

6. Select the sequence of execution of function f1(), f2() & f3() in C# .NET CODE?

1. class base
2. {
3. public void f1() {}
4. public virtual void f2() {}
5. public virtual void f3() {}
6. }
7. class derived :base
8. {
9. new public void f1() {}
10. public override void f2() {}
11. public new void f3() {}
12. }
13. class Program
14. {
15. static void Main(string[] args)
16. {
17. baseclass b = new derived();
18. b.f1 ();
19. b.f2 ();
20. b.f3 ();
21. }
22. }

a)

f1() of derived class get executed

f2() of derived class get executed

f3() of base class get executed

b)

f1() of base class get executed

f2() of derived class get executed

f3() of base class get executed

c)

f1() of base class get executed

f2() of derived class get executed

f3() of derived class get executed

d)

f1() of derived class get executed


f2() of base class get executed

f3() of base class get executed

View Answer
Answer: b
Explanation: None.

7. Which of the following statements is correct?


a) Each derived class does not have its own version of a virtual method
b) If a derived class does not have its own version of virtual method then one in base class is
used
c) By default methods are virtual
d) All of the mentioned
View Answer
Answer: c
Explanation: None.

8. Correct code to be added for overloaded operator – for the following C# code?

1. class csharp
2. {
3. int x, y, z;
4. public csharp()
5. {
6.
7. }
8. public csharp(int a ,int b ,int c)
9. {
10. x = a;
11. y = b;
12. z = c;
13. }
14. Add correct set of code here
15. public void display()
16. {
17. console.writeline(x + " " + y + " " + z);
18. }
19. class program
20. {
21. static void Main(String[] args)
22. {
23. csharp s1 = new csharp(5 ,6 ,8);
24. csharp s3 = new csharp();
25. s3 = - s1;
26. s3.display();
27. }
28. }
29. }
a)

1. public static csharp operator -(csharp s1)


2. {
3. csharp t = new csharp();
4. t.x = s1.x;
5. t.y = s1.y;
6. t.z = -s1.z;
7. return t;
8. }

b)

1. public static csharp operator -(csharp s1)


2. {
3. csharp t = new csharp();
4. t.x = s1.x;
5. t.y = s1.y;
6. t.z = s1.z;
7. return t;
8. }

c)

1. public static csharp operator -(csharp s1)


2. {
3. csharp t = new csharp();
4. t.x = -s1.x;
5. t.y = -s1.y;
6. t.z = -s1.z;
7. return t;
8. }

d) None of the mentioned


View Answer
Answer: c
Explanation: None.

9. Selecting appropriate method out of number of overloaded methods by matching


arguments in terms of number, type and order and binding that selected method to object at
compile time is called?
a) Static binding
b) Static Linking
c) Compile time polymorphism
d) All of the mentioned
View Answer
Answer: d
Explanation: None.

10. Wrong statement about run time polymorphism is?


a) The overridden base method should be virtual, abstract or override
b) An abstract method is implicitly a virtual method
c) An abstract inherited property cannot be overridden in a derived class
d) Both override method and virtual method must have same access level modifier
View Answer
Answer: c
Explanation: None.
5.Select the statement which should be added to the current set of code to get the output as 10 20 ?

class baseclass

protected int a = 20;

class derived : baseclass

int a = 10;

public void math()

/* add code here */

A.Console.writeline( a + ” ” + this.a);

B.Console.Writeline( mybase.a + ” ” + a);

C.console.writeline(a + ” ” + base.a);

D.console.writeline(base.a + ” ” + a);

View Answer

Workspace

Report

Discuss

Answer & Explanation


Answer: Option C

Explanation:

4.In Inheritance concept, which of the following members of base class are accessible to derived class
members?A.static

B.protected

C.private

D.shared

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option B

Explanation:

3.Choose the correct output for given set of code?

enum per

a,

b,

c,

d,

per.a = 10;

Console.writeline(per.b);

A.11

B.1
C.2

D.compile time error

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option D

Explanation:

It will report an error since enum element cannot be assigned a value outside the enum declaration.

2.Which keyword is used to refer baseclass constructor to subclass constructor?A.This

B.static

C.base

D.extend

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option C

Explanation:

1.What will be the output for the given set of code?

namespace ConsoleApplication4

abstract class A
{

public int i;

public abstract void display();

class B: A

public int j;

public int sum;

public override void display()

sum = i + j;

Console.WriteLine(+i + "\n" + +j);

Console.WriteLine("sum is:" +sum);

class Program

static void Main(string[] args)

A obj = new B();

obj.i = 2;

B obj1 = new B();

obj1.j = 10;

obj.display();

Console.ReadLine();
}

A.2, 10

12

B.0, 10

10

C.2, 0

D.0, 0

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option C

Explanation:

Abstract method implementation is processed in subclass ‘B’ .Also the object ‘obj’ of abstract class ‘A’
initializes value of i as 2.The object of class ‘B’ also initializes value of j as 10.Since, the method display()
is called using object of class A which is ‘obj’ and hence i = 2 whereas j = 0 .So, sum = 2.

Output : 2 0

sum is : 2

ASP.NET MCQ Questions And Answers

This section focuses on "ASP.NET" in C#. These Multiple Choice Questions (MCQs) should be practiced to
improve the C# skills required for various interviews (campus interviews, walk-in interviews, company
interviews), placements, entrance exams and other competitive examinations.
1. ASP stands for?

A. Active Server Pages

B. Access Server Pages

C. Active Server Platform

D. Active Server Programming

View Answer

Ans : A

Explanation: ASP stands for Active Server Pages

2. ASP (aka Classic ASP) was introduced in?

A. 1997

B. 1998

C. 1999

D. 2000

View Answer

Ans : B

Explanation: ASP (aka Classic ASP) was introduced in 1998 as Microsoft's first server side scripting
language.

3. Classic ASP pages have the file extension?

A. .aspx

B. .net
C. .asp

D. .cs

View Answer

Ans : C

Explanation: Classic ASP pages have the file extension .asp and are normally written in VBScript.

4. Which of the following is true?

A. ASP.NET Web Forms is not a part of the new ASP.NET Core.

B. ASP.NET Web Forms is an event driven application model.

C. ASP.NET MVC is an MVC application model (Model-View-Controller).

D. All of the above

View Answer

Ans : D

Explanation: All of the above statement are true.

5. ASP.NET is?

A. client side technologies

B. server side technologies

C. Both A and B

D. None of the above


View Answer

Ans : C

Explanation: ASP and ASP.NET are server side technologies.

6. Web.config file is used

A. Configures the time that the server-side codebehind module is called

B. To store the global information and variable definitions for the application

C. To configure the web server

D. To configure the web browser

View Answer

Ans : B

Explanation: Web.config file is used to store the global information and variable definitions for the
application

7. Difference between Response.Write() andResponse.Output.Write().

A. Response.Output.Write() allows you to buffer output

B. Response.Output.Write() allows you to write formatted output

C. Response.Output.Write() allows you to flush output

D. Response.Output.Write() allows you to stream output

View Answer

Ans : B

Explanation: Response.Output.Write() allows you to write formatted output


8. What class does the ASP.NET Web Form class inherit from by default?

A. System.Web.UI.Page

B. System.Web.UI.Form

C. System.Web.GUI.Page

D. System.Web.Form

View Answer

Ans : B

Explanation: System.Web.UI.Form class the ASP.NET Web Form class inherit from by default.

9. Attribute must be set on a validator control for the validation to work

A. ControlToValidate

B. ControlToBind

C. ValidateControl

D. Validate

View Answer

Ans : A

Explanation: Attribute must be set on a validator control for the validation to work ControlToValidate.
10. Default Session data is stored in ASP.Net.

A. StateServer

B. Session Object

C. InProcess

D. All of the above

View Answer

Ans : C

Explanation: InProcess is default Session data is stored in ASP.Net.

6.What will be the output of the given code snippet?

interface calc

void cal(int i);

class displayA :calc

public int x;

public void cal(int i)

x = i * i;

class displayB :calc

public int x;

public void cal(int i)


{

x = i / i;

class Program

public static void Main(string[] args)

displayA arr1 = new displayA();

displayB arr2 = new displayB();

arr1.x = 0;

arr2.x = 0;

arr1.cal(2);

arr2.cal(2);

Console.WriteLine(arr1.x + " " + arr2.x);

Console.ReadLine();

A.0 0

B.2 2

C.4 1

D.1 4

View Answer

Workspace

Report
Discuss

Answer & Explanation

Answer: Option C

Explanation:

class displayA executes the interface calculate by doubling the value of item . Similarly class displayB
implements the interface by dividing item by item.So, variable x of class displayA stores 4 and variable x
of class displayB stores 1.

Output : 4, 1

7.Which keyword is used for correct implementation of an interface in C#.NET?A.interface

B.Interface

C.intf

D.Intf

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option A

Explanation:

8.Correct way to define operator method or to perform operator overloading is?A.public static
op(arglist)

B.public static retval op(arglist)

{
}

C.public static retval operator op(arglist)

D.All of the mentioned

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option C

Explanation:

9.What would be output for the set of code?

class maths

public int x;

public double y;

public int add(int a, int b)

x = a + b;

return x;

public int add(double c, double d)

{
y = c + d;

return (int)y;

public maths()

this.x = 0;

this.y = 0;

class Program

static void Main(string[] args)

maths obj = new maths();

int a = 4;

double b = 3.5;

obj.add(a, a);

obj.add(b, b);

Console.WriteLine(obj.x + " " + obj.y);

Console.ReadLine();

A.4, 3.5

B.8, 0

C.7.5, 8
D.8, 7

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option D

Explanation:

10.What will be the output for the given set of code?

class A

public int i;

public void display()

Console.WriteLine(i);

class B: A

public int j;

public void display()

Console.WriteLine(j);

}
class Program

static void Main(string[] args)

B obj = new B();

obj.i = 1;

obj.j = 2;

obj.display();

Console.ReadLine();

A.0

B.2

C.1

D.Compile time error

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option B

Explanation:

When method display() is called using objects of class ‘B’. The method ‘display()’ for class ‘B’ is called
instead of class ‘A’ as class ‘B’ is inherited by class ‘A’.

Output :2

11.Select the sequence of execution of function f1(), f2() & f3() in C# .NET CODE?
class base

public void f1() {}

public virtual void f2() {}

public virtual void f3() {}

class derived :base

new public void f1() {}

public override void f2() {}

public new void f3() {}

class Program

static void Main(string[] args)

baseclass b = new derived();

b.f1 ();

b.f2 ();

b.f3 ();

A.f1() of derived class get executed

f2() of derived class get executed

f3() of base class get executed


B.f1() of base class get executed

f2() of derived class get executed

f3() of base class get executed

C.f1() of base class get executed

f2() of derived class get executed

f3() of derived class get executed

D.f1() of derived class get executed

f2() of base class get executed

f3() of base class get executed

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option B

Explanation:

12.What will be the correct output for the given code snippet?

class maths

int fact(int n)

int result;

if (n == 1)

return 1;

result = fact(n - 1) * n;
return result;

class Output

static void main(String args[])

maths obj = new maths() ;

Console.WriteLine(obj.fact(4)*obj.fact(2));

A.64

B.60

C.120

D.48

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option D

Explanation:

4! = 4*3*2*1 & 2! = 2*1 .So, 24*2 = 48.

Output : 48

13.The correct way to define a variable of type struct abc among the following is?
struct abc

public string name;

protected internal int age;

private Single sal;

A.abc e = new abc();

B.abc();

C.abc e;

e = new abc;

D.abc e = new abc;

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option A

Explanation:

1. CLR is the .Net equivalent of _____.


A. Java Virtual machine
B. Common Language Runtime
C. Common Type System
D. Common Language Specification

Ans: A

2. Abstract class contains _____.


A. Abstract methods
B. Non Abstract methods
C. Both
D. None

Ans: C

3. The default scope for the members of an interface is _____.


A. private
B. public
C. protected
D. internal

Ans: B

4. Which of the following statements is incorrect about


delegate?
A. Delegates are reference types.
B. Delegates are object-oriented.
C. Delegates are type-safe.
D. Only one can be called using a delegate.

Ans : D

5. The space required for structure variables is allocated on


the stack.
A. True
B. False
C. Maybe
D. Can’t say

Ans: A

6. Which of the following is incorrect about constructors?


A. Defining of constructors can be implicit or explicit.
B. The calling of constructors is explicit.
C. Implicit constructors can be parameterized or parameterless.
D. Explicit constructors can be parameterized or parameterless.

Ans: C
7. Reference is a ___.
A. Copy of class which leads to memory allocation.
B. Copy of class that is not initialized.
C. Pre-defined data type.
D. Copy of class creating by an existing instance.

Ans: D

8. The data members of a class by default are?


A. protected, public
B. private, public
C. private
D. public

Ans: C

9. What is the value returned by function compareTo( ) if the


invoking string is less than the string compared?
A. Zero
B. A value of less than zero
C. A value greater than zero
D. None of the mentioned

Ans: B

10. The correct way to overload +operator?


A. public sample operator + (sample a, sample b)
B. public abstract operator + (sample a, sample b)
C. public static operator + (sample a, sample b)
D. all of the mentioned above

Ans: D

11. Select the two types of threads mentioned in the concept


of multithreading?
A. Foreground
B. Background
C. Only foreground
D. Both foreground and background

Ans: D

12. Choose the wrong statement about properties used in


C#.Net?
A. Each property consists of accessor as getting and set.
B. A property cannot be either read or write-only.
C. Properties can be used to store and retrieve values to and from the data members of
a class.
D. Properties are like actual methods that work like data members.

Ans: A

13. If a class ‘demo’ had ‘add’ property with getting and set
accessors, then which of the following statements will work
correctly?
A. math.add = 20;
B. math m = new math();
m.add = 10;
C. Console.WriteLine(math.add);
D. None of the mentioned

Ans: A

14. What will be the output of the following code snippet?


using System;

class sample

int i;

double k;

public sample (int ii, double kk)

i = ii;

k = kk;
double j = (i) + (k);

Console.WriteLine(j);

~sample()

double j = i - k;

Console.WriteLine(j);

class Program

static void Main(string[] args)

sample s = new sample(9, 2.5);

A. 0 0
B. 11.5 0
C. Compile-time error
D. 11.5 6.5

Ans : D

15. What will be the output of the following code snippet?


using System;

class program

static void Main(string[] args)

int x = 8;
int b = 16;

int c = 64;

x /= c /= b;

Console.WriteLine(x + " " + b+ " " +c);

Console.ReadLine();

A. 2 16 4
B. 4 8 16
C. 2 4 8
D. 8 16 64

Ans: A

16. Struct’s data members are ___ by default.


A. Protected
B. Public
C. Private
D. Default

Ans: C

17. The point at which an exception is thrown is called the


_____.
A. Default point
B. Invoking point
C. Calling point
D. Throw point

Ans: D

18. Which of the following statements are correct for C#


language?
A. Every derived class does not define its own version of the virtual method.
B. By default, the access mode for all methods in C# is virtual.
C. If a derived class, does not define its own version of the virtual method, then the one
present in the base class gets used.
D. All of the above.

Ans: B

19. What will be the output of the following code snippet?


using System;

class sample

public sample()

Console.WriteLine("constructor 1 called");

public sample(int x)

int p = 2;

int u;

u = p + x;

Console.WriteLine("constructor 2 called");

class Program

static void Main(string[] args)

sample s = new sample(4);

sample t = new sample();

Console.ReadLine();
}

A. constructor 1 called
constructor 2 called
B. constructor 2 called
constructor 1 called
C. constructor 2 called
constructor 2 called
D. error

Ans: B

20. Which of the following keywords is used to refer base


class constructor to subclass constructor?
A. this
B. static
C. base
D. extend

Ans: C
1. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. byte varA = 10;
4. byte varB = 20;
5. long result = varA & varB;
6. Console.WriteLine("{0} AND {1} Result :{2}", varA, varB, result);
7. varA = 10;
8. varB = 10;
9. result = varA & varB;
10. Console.WriteLine("{0} AND {1} Result : {2}", varA, varB,
result);
11. Console.ReadLine();
12. }

a) 0, 20
b) 10, 10
c) 0, 10
d) 0, 0
View Answer
Answer: c
Explanation: When ‘OR’ operations is done on the binary values following are the results of
OR.
‘OR’ means addition(+) operation.
0 (false) + 0(false) = 0 (false)
1 (True) + 0(false) = 1 (True)
0(false) + 1(True) = 1 (True)
1(True) + 1(True) = 1 (True)

When using OR operation it gives FALSE only when both the values are FALSE. In all other
cases ‘OR’ operation gives ‘true’.
Output :

10 AND 20 Result :0.


10 AND 10 Result :10.

advertisement

2. What will be the output of the following C# code?

1. public static void Main()


2. {
3. byte varA = 10;
4. byte varB = 20;
5. long result = varA | varB;
6. Console.WriteLine("{0} OR {1} Result :{2}", varA, varB, result);
7. varA = 10;
8. varB = 10;
9. result = varA | varB;
10. Console.WriteLine("{0} OR {1} Result : {2}", varA, varB,
result);
11. }

a) 20, 10
b) 30, 10
c) 10, 20
d) 10, 10
View Answer
Answer: b
Explanation: There are two kinds of Shift operations “Right Shift” and “Left Shift”. Right Shift
operation is used for shifting the bit positions towards right side. Left Shift operation is used
for shifting the bit positions towards left side. When Right Shift operations are done on a
binary value the bits are shifted one position towards the right.
Output :
10 OR 20 Result :30.
10 OR 10 Result :10.

3. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. byte b1 = 0 * AB;
4. byte b2 = 0 * 99;
5. byte temp;
6. temp = (byte) ~b2;
7. Console.Write( temp + " ");
8. temp = (byte) (b1 << b2);
9. Console.Write(temp + " ");
10. temp = (byte)(b2 >> 2);
11. Console.WriteLine(temp);
12. Console.ReadLine();
13. }

a) 101 0 34
b) 103 2 38
c) 102 0 38
d) 101 1 35
View Answer
Answer: c
Explanation: None.
Output:
102 0 38.

4. Which of the following options is not a Bitwise Operator in C#?


a) &, |
b) ^, ~
c) <<, >>
d) +=, -=
View Answer
Answer: d
Explanation: +=, -= are Assignment Operators in C#.

5. What will be the output of the following C# code?

1. bool a = true;
2. bool b = false;
3. a |= b;
4. Console.WriteLine(a);
5. Console.ReadLine();

a) 0
b) 1
c) True
d) False
View Answer
Answer: c
Explanation: ‘bools’ are single bits, and so a bit-wise OR is the same as a logical OR.
Output :
True.

6. Select the relevant C# code set to fill up the blank for the following C# program?

1. static void Main(string[] args)


2. {
3. int x = 10, y = 20;
4. int res;
5. /*_______________*/
6. Console.WriteLine(res);
7. }
a) x % y == 0 ? (x == y ? (x += 2):(y = x + y)):y = y*10;
b) x % y == 0 ? y += 10:(x += 10);
c) x % y == 0 ? return(x) : return (y);
d) All of the mentioned
View Answer
Answer: b
Explanation: None.
Output :
{
int x = 10, y = 20;
int res;
x % y == 0 ? y += 10:(x += 10);
Console.WriteLine(res);
}

7. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. int y = 5;
4. int x;
5. int k = (!(Convert.ToInt32(y) > 10))? x = y + 3 : x = y + 10;
6. Console.WriteLine(x);
7. Console.WriteLine(y);
8. Console.ReadLine();
9. }

a) 5, 8
b) 10, 4
c) 8, 5
d) 11, 8
View Answer
Answer: c
Explanation: Since condition y > 10 is false and !(false) = true. So, first statement x = y + 3 is
executed which is x = 8 with y = 5.
Output:
8, 5.

8. Which among the following is a conditional operator?


a) ‘:?’
b) ?;
c) ?:
d) ??
View Answer
Answer: c
Explanation: By definition.

9. What will be the output of the following C# code?

1. public static void Main(string[] args)


2. {
3. int a = 4;
4. int c = 2;
5. bool b = (a % c == 0 ? true : false);
6. Console.WriteLine(b.ToString());
7. if (a/c == 2)
8. {
9. Console.WriteLine("true");
10. }
11. else
12. {
13. Console.WriteLine("false");
14. }
15. Console.ReadLine();
16. }

a)

True

False

b)

False

True

c)

True

True

d)

False

False

View Answer
Answer: c
Explanation: a % c == 0 condition is true as (4 % 2 == 0). So, b is evaluated as true. Now (a/c
== 2) which means if condition is also true hence it is evaluated as true.
Output:
True
True
10. Arrange the operators in the increasing order as defined in C#.

!=, ?:, &, ++, &&

a) ?: < && < != < & < ++


b) ?: < && < != < ++ < &
c) ?: < && < & <!= < ++
d) ?: < && < != < & < ++
View Answer
Answer: c
Explanation: By definition.

1. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. float a = 16.4f;
4. int b = 12;
5. float c;
6. c = a * ( b + a) / (a - b) ;
7. Console.WriteLine("result is :" +c);
8. Console.ReadLine();
9. }

a) 106
b) 104.789
c) 105.8546
d) 103.45
View Answer
Answer: c
Explanation: The first expression evaluated is ‘b+a’ as both are combined. Next the
expression is multiplied by operand ‘a’ i.e a (b+a) the whole result of numerator is combined
and divided by denominator expression (a – b).
Output:
result is : 105.8546.

2. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. int a, b, c, x;
4. a = 90;
5. b = 15;
6. c = 3;
7. x = a - b / 3 + c * 2 - 1;
8. Console.WriteLine(x);
9. Console.ReadLine();
10. }
a) 92
b) 89
c) 90
d) 88
View Answer
Answer: c
Explanation: The basic evaluation process includes two left to right passes through the
expression. During first pass, the high priority operators are applied and during second pass,
the low priority operators are applied as they are encountered.
First pass :
step 1 : x = 90 - 15 / 3 + 3 * 2 - 1 (15 / 3 evaluated)
step 2 : x = 90 - 5 + 3 * 2 - 1
step 3 : x = 90 - 5 + 3 * 2 -1 (3 * 2 is evaluated)
step 4 : x = 90 - 5 + 6 - 1
Second pass :
step 5 : x = 85 + 6 - 1 (90 - 5 is evaluated)
step 6 : x = 91 - 1(85 + 6 is evaluated)
step 7 : x = 90(91 - 1 is evaluated)
Output : 90.

3. What will be the output of the following C# code?

advertisement
1. static void Main(string[] args)
2. {
3. int a, b, c, x;
4. a = 80;
5. b = 15;
6. c = 2;
7. x = a - b / (3 * c) * ( a + c);
8. Console.WriteLine(x);
9. Console.ReadLine();
10. }

a) 78
b) -84
c) 80
d) 98
View Answer
Answer: b
Explanation: Whenever the parentheses are used, the expressions within parentheses
assumes higher priority. If Two or more sets of parentheses appear one after another as
shown above, the expression contained on the left side is evaluated first and right hand side
last.
First pass:
Step 1: 80 - 15/(3*2)*(80 + 2)
Step 2: 80 - 15/6*82 ((3 * 2) evaluated first and (80 + 2) evaluated
later)
Second pass:
Step 3: 80 - 2*82
Step 4: 80 - 164.
Third pass:
Step 5 : -84. (80 - 164 is evaluated)
Output : -84 .

4. Correct order of priorities are:


a) ‘/’ > ‘%’ > ‘*’ > ‘+’
b) ‘/’ > ‘*’ > ‘%’ > ‘+’
c) ‘*’ > ‘/’ > ‘%’ > ‘+’
d) ‘%’ > ‘*’ > ‘/’ > ‘+’
View Answer
Answer: c
Explanation: By definition.

5. What will be the output of the following C# code?

1. int i, j = 1, k;
2. for (i = 0; i < 3; i++)
3. {
4. k = j++ - ++j;
5. Console.Write(k + " ");
6. }

a) -4 -3 -2
b) -6 -4 -1
c) -2 -2 -2
d) -4 -4 -4
View Answer
Answer: c
Explanation:
Here i = 0, j = 1.
k = 1 - 3 ( j++ = 2 and ++j = 3)
k = -2.
i = 1 , j = 3.
k = 3 - 5 ( j++ = 4 and ++j = 5)
k = -2.
i = 2 , j = 5.
k = 5 - 7 (j++ = 6 and ++j = 7)
k = -2.
Output : -2 , -2 , -2.

6. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. int b= 11;
4. int c = 7;
5. int r = 5;
6. int e = 2;
7. int l;
8. int v = 109;
9. int k;
10. int z,t,p;
11. z = b * c;
12. t = b * b;
13. p = b * r * 2;
14. l = (b * c) + (r * e) + 10;
15. k = v - 8;
16. Console.WriteLine(Convert.ToString(Convert.ToChar(z)) + "
" + Convert.ToString(Convert.ToChar(t)) +
Convert.ToString(Convert.ToChar(p)) +
Convert.ToString(Convert.ToChar(l)) +
Convert.ToString(Convert.ToChar(v)) +
Convert.ToString(Convert.ToChar(k)));
17. Console.ReadLine();
18. }

a) My Name
b) My nAme
c) My name
d) Myname
View Answer
Answer: c
Explanation: Solving the expression l = (b * c) + (r * e) + 10. While from left to right the
parentheses are given preference first.
Step 1 : b * c is evaluated first inside first parentheses.
Step 2 : r * e is evaluated second on right side of first addition symbol.
Step 3 : After evaluating both parentheses 10 is added to value of both.
Output : My name.

7. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. int n = 5;
4. int x = 4;
5. int z, c, k;
6. for (c = 1; c <= n; c++)
7. {
8. for (k = 1; k <= c; k++)
9. {
10. z = 3 * x * x + 2 * x + 4 / x + 8;
11. Console.Write(Convert.ToString(Convert.ToChar(z)));
12. }
13. Console.WriteLine("\n");
14. }
15. Console.ReadLine();
16. }

a)

AA

AAA
AAAA

b)

AB

ABC

ABCD

c)

AA

AAA

AAAA

AAAAA

d)

BC

DEF

DEFG

View Answer
Answer: c
Explanation: Solving the expression for value of ‘z’as 65. With, each passage of loop value
number of ‘z’ increases for each row as
Row 1: A
Row 2: AA
-
-
Row 5: AAAAA
Output : A
AA
AAA
AAAA
AAAAA

8. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. int n = 5;
4. int x = 4;
5. int z, c, k;
6. z = 3 * x * x + 2 * x + 4 / x + 8;
7. for (c = 1; c <= n; c++)
8. {
9. for (k = 1; k <= c; k++)
10. {
11.
Console.Write(Convert.ToString(Convert.ToChar(z)));
12. z++;
13. }
14. Console.WriteLine("\n");
15. }
16. Console.ReadLine();
17. }

a)

AA

AAA

AAAA

AAAAA

b)

AB

ABC
ABCD

ABCDE

c)

BC

DEF

GHIJ

KLMNO

d)

AB

BC

BCD

BCDE

View Answer
9. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. int a , b;
4. int c = 10;
5. int d = 12;
6. int e = 5;
7. int f = 6;
8. a = c * (d + e) / f + d;
9. Console.WriteLine(a);
10. b = c * ( d + e / f + d);
11. Console.WriteLine(b);
12. if (a < b)
13. {
14. Console.WriteLine(" parentheses changes values");
15. }
16. else if (a > b)
17. {
18. Counterintelligence("they have same value");
19. }
20. Console.ReadLine();
21. }

a) They have same value


b) Parentheses changes values
c) Since both have equal values, no conclusion
d) None of the mentioned
View Answer
Answer: b
Explanation: Solving for expression ‘a’ expression inside parentheses are given preference
evaluating (d+e) as 17.
a = 10 * 17/6 + 12.
a = 40.
Solving for expression 'b' expression inside parentheses (d + e /f + d)
are evaluated as (12 + 5/6 + 12)
b = 10 *(12 + 5/6 + 12).
b = 240.
Output : 40
240
parentheses changes values.

10. The correct way of incrementing the operators are:


a) ++ a ++
b) b ++ 1
c) c += 1
d) d =+ 1
View Answer
Answer: c
Explanation: This += is known as short hand operator which is same as variable = variable
+1. Similarly, a-= 1 is a = a-1, a*=1 is a = a * 1. They are used to make code short and
efficient.

1. In mouse cursor option ………………. is a cursor for mouse wheel operations when the mouse
is moving and the window is scrolling horizontally and vertically downward to the left.
A) PanSE

Ads by optAd360

B) PanSW
C) PanSouth
D) PanNW
2. In mouse cursor option …………….. is a cursor for mouse wheel operations when the mouse
is moving and the window is scrolling vertically in an upward direction.
A) PanSE
B) PanSW
C) PanSouth
D) PanNorth

3. ………………… is a signed count of the number of rotation of the mouse wheel.


A) Alfa
B) Delta
C) Wheel rotation
D) Rotation count

4. Most of the functionally of the text box control is simply inherited from the …………….. class,
which is also the a base class for the rich text box control.
A) TextBoxControl
B) RichTextBox
C) TextBoxBase
D) TextBox

Ads by optAd360
5. …………….. control is generally used for editable text although it can also made read only.
A) TextBoxControl
B) RichTextBox
C) TextBoxBase
D) TextBox
6. We can limit the amount of text entered into TextBox control by setting ……………… property
to a specific number of characters.
A) MaxLength
B) TotalLength
C) TextAmount
D) TextLimit

7. TextBox controls also can be used to accept password if the …………….. property is used to
mask characters.
A) PasswordChar
B) PasswordCharacter
C) MaskChar
D) PasswordControl
8. Each hyperlink is a object of the ………………. class and is stored in a collection called links.
A) HyperLink.Link
B) LinkLabel.Link

Ads by optAd360

C) Link.LinkLabel
D) Link.HyperLink
9. Which of the following is NOT the public properties of TextBox objects.
A) AutoSize
B) BackColor
C) BulletIndent
D) MaxLength

10. Which of the following is/are the public methods of TextBox objects.
i) Clear ii) Paste iii) LoadFile iv) Paste
A) i, ii and iii only
B) ii, iii and iv only
C) i, ii and iv only
D) All i, ii, iii and iv

11. Which of the following is NOT the public events of TextBox objects.
A) Autosize changed
B) Readonly Changed
C) Click
D) Link Clicked
12. Which of the following is/are the ways of add scroll bars to a text box using scroll bars
property.
i) None ii) Horizontal iii) Vertical iv) Both

Ads by optAd360

A) i, ii and iii only


B) ii, iii and iv only
C) i, ii and iv only
D) All i, ii, iii and iv
13. In order for the scroll bars to actually appear, the text box’s …………….. property must be
True.
A) MultiLine
B) MultiText
C) Scrolling
D) MultiVisible

14. Which of the following is NOT the public property of RichTextBox Objects.
A) DetectURLs
B) DetectText
C) BulletIndent
D) RightMargin

15. Which of the following is/are the public methods of RichTextBox objects.
i) CanDelete ii) Find iii) LoadFile iv) SelectAll
A) i, ii and iii only
B) ii, iii and iv only
C) i, ii and iv only
D) All i, ii, iii and iv

16. The SaveFile method is used to save the text in a rich text box to disk, and the …………….
method to read it back.

Ads by optAd360

A) LoadFile
B) ReadFile
C) ReadIt
D) ReadBack
17. Which of the following is/are the values of TextAlign property that takes from
content Alignment enumeration.
i) BottomCenter ii) MiddleTop iii) TopLeft iv) MiddleLeft
A) i, ii and iii only
B) i, iii and iv only
C) i, ii and iv only
D) All i, ii, iii and iv

18. Which of the following is/are the public properties of LinkLabel objects.
i) ActiveLinkColor ii) LinkSize iii) LinkBehavior iv) Links
A) i, ii and iii only
B) i, iii and iv only
C) i, ii and iv only
D) All i, ii, iii and iv

19. Hyperlinks can be created using the …………………………………. method in LinkClicked event
handler.
A) System.Diagnostics.Process.Start
B) System.Diagnostics.Hyperlinks.Start
C) System.Diagnostics.Link.Start

Ads by optAd360

D) System.Diagnostics.Link.Event
20. In order to get the text associated with the link, ………………… method can be used.
A) e.Data.Link.ToString
B) e.Link.LinkData.ToString
C) e.LinkData.Link.ToString
D) e.Link.Data.ToString

Answers
1. B) PanSW
2. D) PanNorth
3. B) Delta
4. C) TextBoxBase
5. D) TextBox
6. A) MaxLength
7. A) PasswordChar
8. B) LinkLabel.Link
9. C) BulletIndent
10. C) i, ii and iv only
11. D) Link Clicked
12. D) All i, ii, iii and iv
13. A) MultiLine
14. B) DetectText

Ads by optAd360

15. B) ii, iii and iv only


16. A) LoadFile
17. B) i, iii and iv only
18. B) i, iii and iv only
19. A) System.Diagnostics.Process.Start
20. B) e.Link.LinkData.ToString
1. ………………… property on windows forms, gets or sets the size and location of the form on
the windows desktop.

Ads by optAd360

A) Clientsize
B) Size
C) DesktopBounds
D) Bounds
2. Windows forms public object property, …………….. gets or sets the bounding rectangle for the
form.
A) Clientsize
B) Size
C) DesktopBounds
D) Bounds

3. ………………. method on windows forms public object methods, gets the child control that is
located at the specified co-ordinates.
A) GetChildAtPoint
B) GetNextControl
C) GetChildControl
D) GetChildPoint
4. ……………. method finds the location of the specified screen point to client co-ordinates.
A) PointClient
B) GetClient
C) PointToClient
D) FocusClient

Ads by optAd360
5. ……………. event occurs when a key is pressed while the form has the focus.
A) Keydown
B) Keypress
C) Keyup
D) KeyEnter
6. In the new sub procedure of windows forms, the code calls a procedure named ……………….,
which adds and arranges the controls in the form.
A) InitializeComponent
B) AddComponet
C) NewComponet
D) SubComponent

7. ……………….. keyword is used to refer to the current object.


A) Current
B) Me
C) This
D) ThisForm

8. The possible values for the FormBorderStyle property is/are the following
i) Fixed3D ii) None iii) FixedSingle iv) VariableDialog
A) i, ii and iii only
B) ii, iii and iv only

Ads by optAd360

C) i, ii and iv only
D) All i, ii, iii and iv
9. Form’s ………………. property is used to specify t he initial position on the screen.
A) InitialPosition
B) StartPosition
C) StartScreen
D) InitialScreen

10. We can assign form’s start position property values from the FormStartPosition
enumeration, with the following values.
i) Certerpart ii) CenterScreen iii) Manual iv) Location
A) i, ii and iii only
B) ii, iii and iv only
C) i, ii and iv only
D) All i, ii, iii and iv

11. Which of the following is the correct way of assigning value “centerscreen” for form’s
startposition property.
A) StartPosition.Form1=FormStartPosition.CenterScreen
B) Form1.StartPosition=CenterScreen.FormStartPosition
C) Form1.StartPosition=FormStartPosition.CenterScreen
D) Form1.StartPosition=FormStartPosition.Location.CenterScreen
Ads by optAd360
12. ………….. class is built into the .Net Framework to display messages and accept input from
the user.
A) Msgbox
B) MessageBox
C) InputBox
D) DisplayBox

13. …………….. is a string expression displayed as the message in the dialog box.
A) Prompt
B) Message
C) Expression
D) Dialog

14. Which of the following is/are the possible values of MsgBoxResult returned from MsgBox
function.
i) Ok ii) Cancel iiii) Abort iv) Retry v) Ignore
A) i, ii, iii and v only
B) i, ii, iii and iv only
C) ii, iii, iv and v only
D) All i, ii, iii, iv and v

15. ………………… is one of the MessageBoxDefaultButton enumeration values that specifies


which is the default button for the message box.
A) DefaultButton
B) MessageButton
C) MessageBox

Ads by optAd360

D) DefaultMessage
16. Which of the following is NOT the MessageBoxButtons enumeration value.
A) Ok
B) OkCancel
C) None
D) YesNo
17. Which of the following is/are the MessageBoxIcon enumeration values.
i) Astrisk ii) Error iii) Hand iv) Ok
A) i, ii and iii only
B) ii, iii and iv only
C) i, ii and iv only
D) All i, ii, iii and iv

18. ……………… property returns a value of the ……………….. enumeration when the dialog box
is closed.
A) DockPadding
B) DialogResult
C) Dialog Padding
D) DockResult

19. ……………… property of windows form sets the padding used between docked controls and
the form’s edge.
A) DockPadding
B) DialogResult

Ads by optAd360

C) Dialog Padding
D) DockResult
20. The Get and Set methods in the …………….. property to get and set the text in the text box.
A) Getdata
B) Textdata
C) Textproperty
D) GetSet

Answers
1. C) DesktopBounds
2. D) Bounds
3. A) GetChildAtPoint
4. C) PointToClient
5. B) Keypress
6. A) InitializeComponent
7. B) Me
8. A) i, ii and iii only
9. B) StartPosition
10. A) i, ii and iii only
11. C) Form1.StartPosition=FormStartPosition…
12. B) MessageBox
13. A) Prompt

Ads by optAd360
14. D) All i, ii, iii, iv and v
15. A) DefaultButton
16. C) None
17. A) i, ii and iii only
18. B) DialogResult
19. A) DockPadding
20. B) Textdata
1. What will be the Correct statement in the following C# code?

1. interface a1
2. {
3. void f1();
4. int f2();
5. }
6. class a :a1
7. {
8. void f1()
9. {
10. }
11. int a1.f2()
12. {
13. }
14. }

a) class a is an abstract class


b) A method table would not be created for class a
c) The definition of f1() in class a should be void a1.f1()
d) None of the mentioned
View Answer
Answer: c
Explanation: None.

2. Choose the wrong statement about ‘INTERFACE’ in C#.NET?


a) An explicitly implemented member could be accessed from an instance of the interface
b) Interfaces are declared public automatically
c) An interface could not contain signature of the indexer
d) None of the mentioned
View Answer
Answer: c
Explanation: None.

3. What will be the Correct statement in the following C# code?

1. interface a1
2. {
3. void f1();
4. void f2();
5. }
6. class a :a1
7. {
8. private int i;
9. void a1.f1()
10. {
11. }
12. }

a) Class a could not have an instance data


b) Class a is an abstract class
c) Class a fully implements the interface a1
d) None of the mentioned
View Answer
Answer: b
Explanation: None.
advertisement

4. What will be the Correct statement in the following C# code?

1. interface abc
2. {
3. String FirstName
4. {
5. get;
6. set;
7. }
8. String LastName
9. {
10. get;
11. set;
12. }
13. void print();
14. void stock();
15. int fun();
16. }

a) Functions should be declared inside an interface


b) It is workable code
c) Properties cannot be declared inside an interface
d) None of the mentioned
View Answer
Answer: b
Explanation: None.

5. What will be the output of the following C# code?

1. interface calc
2. {
3. void cal(int i);
4. }
5. public class maths :calc
6. {
7. public int x;
8. public void cal(int i)
9. {
10. x = i * i;
11. }
12. }
13. class Program
14. {
15. public static void Main(string[] args)
16. {
17. display arr = new display();
18. arr.x = 0;
19. arr.cal(2);
20. Console.WriteLine(arr.x);
21. Console.ReadLine();
22. }
23. }

a) 0
b) 2
c) 4
d) None of the mentioned
View Answer
Answer: c
Explanation: None.
Output :
4

6. What will be the output of the following C# code?

1. interface calc
2. {
3. void cal(int i);
4. }
5. class displayA :calc
6. {
7. public int x;
8. public void cal(int i)
9. {
10. x = i * i;
11. }
12. }
13. class displayB :calc
14. {
15. public int x;
16. public void cal(int i)
17. {
18. x = i / i;
19. }
20. }
21. class Program
22. {
23. public static void Main(string[] args)
24. {
25. displayA arr1 = new displayA();
26. displayB arr2 = new displayB();
27. arr1.x = 0;
28. arr2.x = 0;
29. arr1.cal(2);
30. arr2.cal(2);
31. Console.WriteLine(arr1.x + " " + arr2.x);
32. Console.ReadLine();
33. }
34. }

a) 0 0
b) 2 2
c) 4 1
d) 1 4
View Answer
Answer: c
Explanation: class displayA executes the interface calculate by doubling the value of item.
Similarly class displayB implements the interface by dividing item by item. So, variable x of
class displayA stores 4 and variable x of class displayB stores 1.
Output :
4, 1

7. What will be the output of the following C# code?

1. interface i1
2. {
3. void fun();
4. }
5. interface i2
6. {
7. void fun();
8. }
9. public class maths :i1, i2
10. {
11. void i1.fun()
12. {
13. Console.WriteLine("i1.fun");
14. }
15. void i2.fun()
16. {
17. Console.WriteLine("i2.fun");
18. }
19. }
20. class Program
21. {
22. static void Main(string[] args)
23. {
24. Sample obj = new Sample();
25. i1 i = (i1) obj;
26. i.fun();
27. i2 ii = (i2) obj;
28. ii.fun();
29. }
30. }

a) i1.fun
b)
i2.fun

i1.fun

c) 0
d)

i1.fun

i2.fun

View Answer
Answer: d
Explanation: None.

8. What will be the correct way to implement the interface in the following C# code?

1. interface abc
2. {
3. string name
4. {
5. get;
6. set;
7. }
8. }

a)

class emp :employee


{
private string str;
public string firstname;
{
get
{
return str;
}
set
{
str = value;
}
}
}

b)

class emp :implements person


{
private string str;
public string firstname
{
get
{
return str;
}
set
{
str = value;
}
}
}

c)

class emp: implements person


{
private string str;
public string person.firstname
{
get
{
return str;
}
set
{
str = value;
}
}
}

d) None of the mentioned


View Answer
Answer: a
Explanation: None.

9. What will be the output of the following C# code?

1. interface i1
2. {
3. void f1();
4. }
5. interface i2 :i1
6. {
7. void f2();
8. }
9. public class maths :i2
10. {
11. public void f2()
12. {
13. Console.WriteLine("fun2");
14. }
15. public void f1()
16. {
17. Console.WriteLine("fun1");
18. }
19. }
20. class Program
21. {
22. static Void Main()
23. {
24. maths m = new maths();
25. m.f1();
26. m.f2();
27. }
28. }

a) fun2
b) fun1
c)

fun1

fun2

d)

fun2

fun1

View Answer
Answer: c
Explanation: None.

10. In order to avoid ambiguity among an interface derived from two base interfaces with
same method name(and signature), the right code among the following C# codes is?
a)

1. interface i1
2. {
3. void m1();
4. }
5. interface i2
6. {
7. void m1();
8. }
9. interface i3 :i1, i2
10. {
11. }
12. class c3 :i3
13. {
14. void i1.m1()
15. {
16. }
17. void i1.m1()
18. {
19. }
20. }

b)

interface i1
{
void m1();
}
interface i2
{
void m1();
}
interface i3 :i1, i2
{
}
class c3 :i3
{
void i1.i2.m1()
{
}
}

c)

interface i1
{
void m1();
}
interface i2
{
void m1();
}
interface i3 :i1, i2
{
}
class c3 :i3
{
void i1.m1()
{
}
void i2.m1()
{
}
}

d) All of the mentioned


View Answer
Answer: c
Explanation: None.
1. What is MVC (Model View Controller)?

Model–view–controller (MVC) is a software architectural pattern for implementing user


interfaces. It divides a given software application into three interconnected parts, so as to
separate internal representation of information from the way that information is presented to or
accepted from the user.

MVC is a framework for building web applications using an MVC (Model View Controller)
design:

 The Model represents the application core (for instance a list of database records).
 The View displays the data (the database records).
 The Controller handles the input (to the database records).

The MVC model also provides full control over HTML, CSS, and JavaScript.

The MVC model defines web applications with 3 logic layers,

 The business layer (Model logic)


 The display layer (View logic)
 The input control (Controller logic)
The Model is the part of the application that handles the logic for the application data.

Often model objects retrieve data (and store data) from a database.

The View is the part of the application that handles the display of the data.

Most often the views are created from the model data.

The Controller is the part of the application that handles user interaction.

Typically controllers read data from a view, control user input, and send input data to the model.

The MVC separation helps you manage complex applications because you can focus on one
aspect a time. For example, you can focus on the view without depending on the business logic.
It also makes it easier to test an application.

The MVC separation also simplifies group development. Different developers can work on the
view, the controller logic, and the business logic in parallel.

Learn more about ASP.NET MVC here: Overview Of ASP.NET MVC

2. What are the advantages of MVC?

Multiple view support

Due to the separation of the model from the view, the user interface can display multiple views
of the same data at the same time.
Change Accommodation

User interfaces tend to change more frequently than business rules (different colors, fonts,
screen layouts, and levels of support for new devices such as cell phones or PDAs) because
the model does not depend on the views, adding new types of views to the system generally
does not affect the model. As a result, the scope of change is confined to the view.

SoC – Separation of Concerns

Separation of Concerns is one of the core advantages of ASP.NET MVC. The MVC framework
provides a clean separation of the UI, Business Logic, Model or Data.

More Control

The ASP.NET MVC framework provides more control over HTML, JavaScript, and CSS than the
traditional Web Forms.

Testability

ASP.NET MVC framework provides better testability of the Web Application and good support
for test driven development too.

Lightweight

ASP.NET MVC framework doesn’t use View State and thus reduces the bandwidth of the
requests to an extent.

Full features of ASP.NET


One of the key advantages of using ASP.NET MVC is that it is built on top of the ASP.NET
framework and hence most of the features of the ASP.NET like membership providers, roles,
etc can still be used.

Here is a detailed article on Creating a Simple Application Using MVC 4.0.

3. Explain MVC application life cycle?

Any web application has two main execution steps, first understanding the request and
depending on the type of the request sending out an appropriate response. MVC application life
cycle is not different it has two main phases, first creating the request object and second
sending our response to the browser.

Creating the request object,

The request object creation has four major steps. The following is a detailed explanation of the
same.
Step 1 - Fill route

MVC requests are mapped to route tables which in turn specify which controller and action to be
invoked. So if the request is the first request the first thing is to fill the rout table with routes
collection. This filling of the route table happens the global.asax file.

Step 2 - Fetch route

Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData”
object which has the details of which controller and action to invoke.

Step 3 - Request context created

The “RouteData” object is used to create the “RequestContext” object.

Step 4 - Controller instance created

This request object is sent to “MvcHandler” instance to create the controller class instance.
Once the controller class object is created it calls the “Execute” method of the controller class.

Creating a Response object

This phase has two steps executing the action and finally sending the response as a result to
the view.

Here is a complete article on ASP.Net MVC Life Cycle.


4. List out different return types of a controller action method?

There are total of nine return types we can use to return results from the controller to view.

The base type of all these result types is ActionResult.

ViewResult (View)

This return type is used to return a webpage from an action method.

PartialviewResult (Partialview)

This return type is used to send a part of a view that will be rendered in another view.

RedirectResult (Redirect)

This return type is used to redirect to any other controller and action method depending on the
URL.

RedirectToRouteResult (RedirectToAction, RedirectToRoute)

This return type is used when we want to redirect to any other action method.

ContentResult (Content)

This return type is used to return HTTP content type like text/plain as the result of the action.
jsonResult (json)

This return type is used when we want to return a JSON message.

javascriptResult (javascript)

This return type is used to return JavaScript code that will run in the browser.

FileResult (File)

This return type is used to send binary output in response.

EmptyResult

This return type is used to return nothing (void) in the result.

Here is a complete article on Various Return Types From MVC Controller.

5. What are the Filters in MVC?

In MVC, controllers define action methods and these action methods generally have a one-to-
one relationship with UI controls such as clicking a button or a link, etc. For example, in one of
our previous examples, the UserController class contained methods UserAdd, UserDelete, etc.

But many times we would like to perform some action before or after a particular operation. For
achieving this functionality, ASP.NET MVC provides a feature to add pre and post-action
behaviors on the controller's action methods.
Types of Filters

ASP.NET MVC framework supports the following action filters,

 Action Filters

Action filters are used to implement logic that gets executed before and after a controller
action executes. We will look at Action Filters in detail in this chapter.

 Authorization Filters

Authorization filters are used to implement authentication and authorization for controller
actions.

 Result Filters

Result filters contain logic that is executed before and after a view result is executed. For
example, you might want to modify a view result right before the view is rendered to the
browser.

 Exception Filters

Exception filters are the last type of filter to run. You can use an exception filter to handle
errors raised by either your controller actions or controller action results. You can
also use exception filters to log errors.

Action filters are one of the most commonly used filters to perform additional data processing, or
manipulating the return values or canceling the execution of an action or modifying the view
structure at run time.
Here is a complete article on Understanding Filters in MVC.

6. What are Action Filters in MVC?

Answer - Action Filters

Action Filters are additional attributes that can be applied to either a controller section or the
entire controller to modify the way in which action is executed. These attributes are special .NET
classes derived from System.Attribute which can be attached to classes, methods, properties,
and fields.

ASP.NET MVC provides the following action filters,

 Output Cache

This action filter caches the output of a controller action for a specified amount of time.

 Handle Error

This action filter handles errors raised when a controller action executes.

 Authorize

This action filter enables you to restrict access to a particular user or role.

Now we will see the code example to apply these filters on an example controller
ActionFilterDemoController. (ActionFilterDemoController is just used as an example. You can
use these filters on any of your controllers.)
Output Cache

Code Example

Specifies the return value to be cached for 10 seconds.

1. publicclassActionFilterDemoController: Controller
2. {
3. [HttpGet]
4. OutputCache(Duration = 10)]
5. publicstringIndex()
6. {
7. returnDateTime.Now.ToString("T");
8.
9. }
10. }

Learn more here: ASP.NET MVC with Action Filters

7. Explain what is routing in MVC? What are the three segments for routing
important?

Routing is a mechanism to process the incoming URL that is more descriptive and gives the
desired response. In this case, URL is not mapped to specific files or folder as was the case of
earlier days web sites.

There are two types of routing (after the introduction of ASP.NET MVC 5).

1. Convention-based routing - to define this type of routing, we call MapRoute method and
set its unique name, URL pattern and specify some default values.

2. Attribute-based routing - to define this type of routing, we specify the Route attribute in
the action method of the controller.

Routing is the URL pattern that is mapped together to a handler,routing is responsible for
incoming browser request for particular MVC controller. In other ways let us say routing help
you to define a URL structure and map the URL with controller. There are three segments for
routing that are important,

1. ControllerName
2. ActionMethodName
3. Parammeter

Code Example

ControllerName/ActionMethodName/{ParamerName} and also route map coding written in a


Global.asax file.

Learn more here - Routing in MVC.

8. What is Route in MVC? What is Default Route in MVC?

A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such
as a .aspx file in a Web Forms application. A handler can also be a class that processes the
request, such as a controller in an MVC application. To define a route, you create an instance of
the Route class by specifying the URL pattern, the handler, and optionally a name for the route.

You add the route to the application by adding the Route object to the static Routes property of
the RouteTable class. The Routesproperty is a RouteCollection object that stores all the routes
for the application.

You typically do not have to write code to add routes in an MVC application. Visual Studio
project templates for MVC include preconfigured URL routes. These are defined in the MVC
Application class, which is defined in the Global.asax file.

Route definition Example of matching URL

{controller}/{action}/{id} /Products/show/beverages

{table}/Details.aspx /Products/Details.aspx

blog/{action}/{entry} /blog/show/123
{reporttype}/{year}/{month}/{day} /sales/2008/1/5

{locale}/{action} /US/show

{language}-{country}/{action} /en-US/show

Default Route

The default ASP.NET MVC project templates add a generic route that uses the following URL
convention to break the URL for a given request into three named segments.

URL: "{controller}/{action}/{id}"

This route pattern is registered via a call to the MapRoute() extension method of
RouteCollection.

9. Mention what is the difference between Temp data, View, and View Bag?

In ASP.NET MVC there are three ways to pass/store data between the controllers and views.

ViewData

1. ViewData is used to pass data from controller to view.


2. It is derived from ViewDataDictionary class.
3. It is available for the current request only.
4. Requires typecasting for complex data types and checks for null values to avoid an
error.
5. If redirection occurs, then its value becomes null.

ViewBag

1. ViewBag is also used to pass data from the controller to the respective view.
2. ViewBag is a dynamic property that takes advantage of the new dynamic features in C#
4.0
3. It is also available for the current request only.
4. If redirection occurs, then its value becomes null.
5. It doesn’t require typecasting for the complex data type.

TempData

1. TempData is derived from TempDataDictionary class


2. TempData is used to pass data from the current request to the next request
3. It keeps the information for the time of an HTTP Request. This means only from one
page to another. It helps to maintain the data when we move from one controller to
another controller or from one action to another action
4. It requires typecasting for complex data types and checks for null values to avoid an
error. Generally, it is used to store only one time messages like the error messages and
validation messages

Learn more here: Difference Between ViewData, ViewBag, and TempData

10. What is Partial View in MVC?

A partial view is a chunk of HTML that can be safely inserted into an existing DOM. Most
commonly, partial views are used to componentize Razor views and make them easier to build
and update. Partial views can also be returned directly from controller methods. In this case, the
browser still receives text/html content but not necessarily HTML content that makes up an
entire page. As a result, if a URL that returns a partial view is directly invoked from the address
bar of a browser, an incomplete page may be displayed. This may be something like a page that
misses title, script and style sheets. However, when the same URL is invoked via a script, and
the response is used to insert HTML within the existing DOM, then the net effect for the end-
user may be much better and nicer.

Partial view is a reusable view (like a user control) which can be embedded inside another view.
For example, let’s say all the pages of your site have a standard structure with left menu,
header, and footer as in the following image,
Learn more here - Partial View in MVC

11. Explain what is the difference between View and Partial View?

View

 It contains the layout page.


 Before any view is rendered, viewstart page is rendered.
 A view might have markup tags like body, HTML, head, title, meta etc.
 The view is not lightweight as compare to Partial View.
Partial View

 It does not contain the layout page.


 Partial view does not verify for a viewstart.cshtml.We cannot put common code for a
partial view within the viewStart.cshtml.page.
 Partial view is designed specially to render within the view and just because of that it
does not consist any mark up.
 We can pass a regular view to the RenderPartial method.

Learn more here - Partial View in MVC

12. What are HTML helpers in MVC?

With MVC, HTML helpers are much like traditional ASP.NET Web Form controls.

Just like web form controls in ASP.NET, HTML helpers are used to modify HTML. But HTML
helpers are more lightweight. Unlike Web Form controls, an HTML helper does not have an
event model and a view state.

In most cases, an HTML helper is just a method that returns a string.

With MVC, you can create your own helpers, or use the built in HTML helpers.

Standard HTML Helpers

HTML Links

The easiest way to render an HTML link in is to use the HTML.ActionLink() helper.With MVC,
the Html.ActionLink() does not link to a view. It creates a link to a controller action.

ASP Syntax

1. <%=Html.ActionLink("About this Website", "About")%>


The first parameter is the link text, and the second parameter is the name of the controller
action.

The Html.ActionLink() helper above, outputs the following HTML:

1. <a href="/Home/About">About this Website</a>

The Html.ActionLink() helper has several properties:

 Property Description.
 .linkText The link text (label).
 .actionName The target action.
 .routeValues The values passed to the action.
 .controllerName The target controller.
 .htmlAttributes The set of attributes to the link.
 .protocol The link protocol.
 .hostname The host name for the link.
 .fragment The anchor target for the link.

HTML Form Elements

There following HTML helpers can be used to render (modify and output) HTML form elements:

 BeginForm()
 EndForm()
 TextArea()
 TextBox()
 CheckBox()
 RadioButton()
 ListBox()
 DropDownList()
 Hidden()
 Password()

ASP.NET Syntax C#

1. <%= Html.ValidationSummary("Create was unsuccessful. Please corre


ct the errors and try again.") %>
2. <% using (Html.BeginForm()){%>
3. <p>
4. <label for="FirstName">First Name:</label>
5. <%= Html.TextBox("FirstName") %>
6. <%= Html.ValidationMessage("FirstName", "*") %>
7. </p>
8. <p>
9. <label for="LastName">Last Name:</label>
10. <%= Html.TextBox("LastName") %>
11. <%= Html.ValidationMessage("LastName", "*")
%>
12. </p>
13. <p>
14. <label for="Password">Password:</label>
15. <%= Html.Password("Password") %>
16. <%= Html.ValidationMessage("Password", "*") %>
17. </p>
18. <p>
19. <label for="Password">Confirm Password:</label>

20. <%= Html.Password("ConfirmPassword") %>


21. <%= Html.ValidationMessage("ConfirmPassword"
, "*") %>
22. </p>
23. <p>
24. <label for="Profile">Profile:</label>
25. <%= Html.TextArea("Profile", new {cols=60, rows=
10})%>
26. </p>
27. <p>
28. <%= Html.CheckBox("ReceiveNewsletter") %>
29. <label for="ReceiveNewsletter" style="displa
y:inline">Receive Newsletter?</label>
30. </p>
31. <p>
32. <input type="submit" value="Register" />
33. </p>
34. <%}%>

Learn more here - HTML Helpers in MVC: Part 1

13. Explain attribute based routing in MVC?

In ASP.NET MVC 5.0 we have a new attribute route,cBy using the "Route" attribute we can
define the URL structure. For example in the below code we have decorated the "GotoAbout"
action with the route attribute. The route attribute says that the "GotoAbout" can be invoked
using the URL structure "Users/about".

Hide Copy Code


1. public class HomeController: Controller
2. {
3. [Route("Users/about")]
4. publicActionResultGotoAbout()
5. {
6. return View();
7. }
8. }

Learn more here - Attribute Based Routing in ASP.Net MVC 5

14. What is TempData in MVC?

TempData is a dictionary object to store data temporarily. It is a TempDataDictionary class type


and instance property of the Controller base class.

TempData is able to keep data for the duration of a HTP request, in other words it can keep live
data between two consecutive HTTP requests. It will help us to pass the state between action
methods. TempData only works with the current and subsequent request. TempData uses a
session variable to store the data. TempData Requires type casting when used to retrieve data.

TempDataDictionary is inherited from the IDictionary<string, object>,


ICollection<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>> and
IEnumerable interfaces.

Example

1. public ActionResult FirstRequest()


2. {
3. List < string > TempDataTest = new List < string > ();
4. TempDataTest.Add("Tejas");
5. TempDataTest.Add("Jignesh");
6. TempDataTest.Add("Rakesh");
7. TempData["EmpName"] = TempDataTest;
8. return View();
9. }
10. public ActionResult ConsecutiveRequest()
11. {
12. List < string > modelData = TempData["EmpName"] as List < str
ing > ;
13. TempData.Keep();
14. return View(modelData);
15. }

Learn more here - All About the TempData in MVC

15. What is Razor in MVC?

ASP.NET MVC has always supported the concept of "view engines" - which are the pluggable
modules that implement different template syntax options. The "default" view engine for
ASP.NET MVC uses the same .aspx/.ascx/. master file templates as ASP.NET Web Forms.
Other popular ASP.NET MVC view engines are Spart&Nhaml.

MVC 3 has introduced a new view engine called Razor.

Why is Razor?

1. Compact & Expressive.


2. Razor minimizes the number of characters and keystrokes required in a file, and enables
a fast coding workflow. Unlike most template syntaxes, you do not need to interrupt your
coding to explicitly denote server blocks within your HTML. The parser is smart enough
to infer this from your code. This enables a really compact and expressive syntax which
is clean, fast and fun to type.
3. Easy to Learn: Razor is easy to learn and enables you to quickly be productive with a
minimum of effort. We can use all your existing language and HTML skills.
4. Works with any Text Editor: Razor doesn't require a specific tool and enables you to be
productive in any plain old text editor (notepad works great).
5. Has great Intellisense:
6. Unit Testable: The new view engine implementation will support the ability to unit test
views (without requiring a controller or web-server, and can be hosted in any unit test
project - no special app-domain required).

Learn more here - Brief Introduction to MVC3

16. Differences between Razor and ASPX View Engine in MVC?

Razor View Engine VS ASPX View Engine


Razor View Engine ASPX View Engine (Web form view engine)

The namespace used by the Razor The namespace used by the ASPX View Engine is
View Engine is System.Web.Razor System.Web.Mvc.WebFormViewEngine

The file extensions used by the


The file extensions used by the Web Form View Engines
Razor View Engine are different
are like ASP.Net web forms. It uses the ASPX extension to
from a web form view engine. It
view the aspc extension for partial views or User Controls
uses cshtml with C# and vbhtml
or templates and master extensions for layout/master
with vb for views, partial view,
pages.
templates and layout pages.

The Razor View Engine is an


advanced view engine that was
A web form view engine is the default view engine and
introduced with MVC 3.0. This is
available from the beginning of MVC
not a new language but it is
markup.

Razor has a syntax that is very


The web form view engine has syntax that is the same as
compact and helps us to reduce
an ASP.Net forms application.
typing.

The Razor View Engine uses @ to The ASPX/web form view engine uses "<%= %>" or "<%:
render server-side content. %>" to render server-side content.

By default all text from an @ There is a different syntax ("<%: %>") to make text HTML
expression is HTML encoded. encoded.

Razor does not require the code


block to be closed, the Razor View
Engine parses itself and it is able to A web form view engine requires the code block to be
decide at runtime which is a content closed properly otherwise it throws a runtime exception.
element and which is a code
element.

The Razor View Engine prevents


Cross-Site Scripting (XSS) attacks A web form View engine does not prevent Cross-Site
by encoding the script or HTML Scripting (XSS) attacks.
tags before rendering to the view.

Web Form view engine does not support Test Driven


The Razor Engine supports Test
Development (TDD) because it depends on the
Driven Development (TDD).
System.Web.UI.Page class to make the testing complex.
Razor uses "@* … *@" for The ASPX View Engine uses "<!--...-->" for markup and "/*
multiline comments. … */" for C# code.

There are only three transition


There are only three transition characters with the Razor
characters with the Razor View
View Engine.
Engine.

The Razor View Engine is a bit slower than the ASPX View Engine.

Conclusion

Razor provides a new view engine with a streamlined code for focused templating. Razor's
syntax is very compact and improves the readability of the markup and code. By default, MVC
supports ASPX (web forms) and Razor View Engine. MVC also supports third-party view
engines like Spark, Nhaml, NDjango, SharpDOM and so on. ASP.NET MVC is open source.

Learn more here - ASPX View Engine VS Razor View Engine

17. What are the Main Razor Syntax Rules?

Answer

 Razor code blocks are enclosed in @{ ... }


 Inline expressions (variables and functions) start with @
 Code statements end with semicolon
 Variables are declared with the var keyword
 Strings are enclosed with quotation marks
 C# code is case sensitive
 C# files have the extension .cshtml

C# Example

1. <!-- Single statement block -->


2. @ {
3. varmyMessage = "Hello World";
4. }
5. <!-- Inline expression or variable -->
6. < p > The value of myMessage is: @myMessage < /p>
7. <!-- Multi-statement block -->
8. @ {
9. var greeting = "Welcome to our site!";
10. varweekDay = DateTime.Now.DayOfWeek;
11. vargreetingMessage = greeting + " Here in Huston it is:
" + weekDay;
12. } < p > The greeting is: @greetingMessage < /p>

Learn more here - Introduction to Microsoft ASP.NET MVC 3 Razor View Engine

18. How do you implement Forms authentication in MVC?

Answer

Authentication is giving access to the user for a specific service by verifying his/her identity
using his/her credentials like username and password or email and password. It assures that
the correct user is authenticated or logged in for a specific service and the right service has
been provided to the specific user based on their role that is nothing but authorization.

ASP.NET forms authentication occurs after IIS authentication is completed. You can configure
forms authentication by using forms element with in web.config file of your application. The
default attribute values for forms authentication are shown below,

1. <system.web>
2. <authenticationmode="Forms">
3. <formsloginUrl="Login.aspx" protection="All" timeout="30"
name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="
true" defaultUrl="default.aspx" cookieless="UseDeviceProfile" ena
bleCrossAppRedirects="false" />
4. </authentication>
5. </system.web>

The FormsAuthentication class creates the authentication cookie automatically when


SetAuthCookie() or RedirectFromLoginPage() methods are called. The value of authentication
cookie contains a string representation of the encrypted and signed FormsAuthenticationTicket
object.

Learn more here - Form Authentication in MVC 5: Part 1


19. Explain Areas in MVC?

Answer

From ASP.Net MVC 2.0 Microsoft provided a new feature in MVC applications, Areas. Areas
are just a way to divide or “isolate” the modules of large applications in multiple or separated
MVC. like,

When you add an area to a project, a route for the area is defined in an AreaRegistration file.
The route sends requests to the area based on the request URL. To register routes for areas,
you add code to theGlobal.asax file that can automatically find the area routes in the
AreaRegistration file.

AreaRegistration.RegisterAllAreas();

Benefits of Area in MVC

1. Allows us to organize models, views and controllers into separate functional sections of
the application, such as administration, billing, customer support and much more.
2. Easy to integrate with other Areas created by another.
3. Easy for unit testing.

Learn more here - What Are Areas in ASP.Net MVC - Part 6

20. Explain the need of display mode in MVC?

Answer

DisplayModes give you another level of flexibility on top of the default capabilities we saw in the
last section. DisplayModes can also be used along with the previous feature so we will simply
build off of the site we just created.

Using display modes involves in 2 steps

1. We should register Display Mode with a suffix for particular browser using
“DefaultDisplayMode”e class inApplication_Start() method in the Global.asax file.
2. View name for particular browser should be appended with suffix mentioned in first step.

1. Desktop browsers (without any suffix. e.g.: Index.cshtml, _Layout.cshtml).


2. Mobile browsers (with a suffix “Mobile”. e.g.: Index.Mobile.cshtml,Layout.Mobile.cshtml)
If you want design different pages for different mobile device browsers (any different
browsers) and render them depending on the browser requesting. To handle these
requests you can register custom display modes. We can do that using
DisplayModeProvider.Instance.Modes.Insert(int index, IDisplayMode item) method.

Learn more here - Display Mode Provider in MVC 5 Application

21. Explain the concept of MVC Scaffolding?

Answer

ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. Visual
Studio 2013 includes pre-installed code generators for MVC and Web API projects. You add
scaffolding to your project when you want to quickly add code that interacts with data models.
Using scaffolding can reduce the amount of time to develop standard data operations in your
project.

Scaffolding consists of page templates, entity page templates, field page templates, and filter
templates. These templates are called Scaffold templates and allow you to quickly build a
functional data-driven Website.
Scaffolding Templates

Create

It creates a View that helps in creating a new record for the Model. It automatically generates a
label and input field for each property in the Model.

Delete

It creates a list of records from the model collection along with the delete link with delete record.

Details

It generates a view that displays the label and an input field of the each property of the Model in
the MVC framework.

Edit
It creates a View with a form that helps in editing the current Model. It also generates a form
with label and field for each property of the model.

List

It generally creates a View with the help of a HTML table that lists the Models from the Model
Collection. It also generates a HTML table column for each property of the Model.

Learn more here - Terminologies in MVC: Part 3 (Scaffolding)

22. What is Route Constraints in MVC?

Answer

Routing is a great feature of MVC, it provides a REST based URL that is very easy to remember
and improves page ranking in search engines.

This article is not an introduction to Routing in MVC, but we will learn a few features of routing
and by implementing them we can develop a very flexible and user-friendly application. So, let's
start without wasting valuable time.

Add constraint to URL

This is very necessary for when we want to add a specific constraint to our URL. Say, for
example we want a URL.

So, we want to set some constraint string after our host name. Fine, let's see how to implement
it.
It's very simple to implement, just open the RouteConfig.cs file and you will find the routing
definition in that. And modify the routing entry as in the following. We will see that we have
added “abc” before.

Controller name, now when we browse we need to specify the string in the URL, as in the
following:

Learn more here - Route Constraints in MVC

23. What is Razor View Engine in MVC?

Answer

ASP.NET MVC has always supported the concept of "view engines" that are the pluggable
modules that implement various template syntax options. The "default" view engine for
ASP.NET MVC uses the same .aspx/.ascx/.master file templates as ASP.NET Web Forms. In
this article I go through the Razor View Engine to create a view of an application. "Razor" was in
development beginning in June 2010 and was released for Microsoft Visual Studio in January
2011.
Razor is not a new programming language itself, but uses C# syntax for embedding code in a
page without the ASP.NET delimiters: <%= %>. It is a simple-syntax view engine and was
released as part of ASP.NET MVC 3. The Razor file extension is "cshtml" for the C# language.
It supports TDD (Test Driven Development) because it does not depend on the
System.Web.UI.Page class.

Learn more here - Getting Started with Razor View Engine in MVC 3

24. What is Output Caching in MVC?

Answer

The main purpose of using Output Caching is to dramatically improve the performance of an
ASP.NET MVC Application. It enables us to cache the content returned by any controller
method so that the same content does not need to be generated each time the same controller
method is invoked. Output Caching has huge advantages, such as it reduces server round trips,
reduces database server round trips, reduces network traffic etc.

Keep the following in mind,

 Avoid caching contents that are unique per user.


 Avoid caching contents that are accessed rarely.
 Use caching for contents that are accessed frequently.

Let's take an example. My MVC application displays a list of database records on the view page
so by default each time the user invokes the controller method to see records, the application
loops through the entire process and executes the database query. And this can actually
decrease the application performance. So, we can advantage of the "Output Caching" that
avoids executing database queries each time the user invokes the controller method. Here the
view page is retrieved from the cache instead of invoking the controller method and doing
redundant work.

Cached Content Locations

In the above paragraph I said, in Output Caching the view page is retrieved from the cache, so
where is the content cached/stored?
Please note, there is no guarantee that content will be cached for the amount of time that we
specify. When memory resources become low, the cache starts evicting content automatically.

OutputCache label has a "Location" attribute and it is fully controllable. Its default value is "Any",
however there are the following locations available; as of now, we can use any one.

1. Any
2. Client
3. Downstream
4. Server
5. None
6. ServerAndClient

With "Any", the output cache is stored on the server where the request was processed. The
recommended store cache is always on the server very carefully. You will learn about some
security related tips in the following "Don't use Output Cache".

Learn more here - Output Caching in MVC

25. What is Bundling and Minification in MVC?

Answer

Bundling and minification are two new techniques introduced to improve request load time. It
improves load time by reducing the number of requests to the server and reducing the size of
requested assets (such as CSS and JavaScript).

Bundling

It lets us combine multiple JavaScript (.js) files or multiple cascading style sheet (.css) files so
that they can be downloaded as a unit, rather than making individual HTTP requests.

Minification
It squeezes out whitespace and performs other types of compression to make the downloaded
files as small as possible. At runtime, the process identifies the user agent, for example IE,
Mozilla, etc. and then removes whatever is specific to Mozilla when the request comes from IE.

Learn more here - Bundling and Minification in Visual Studio 2012 or Migrate Existing Website

26. What is Validation Summary in MVC?

Answer

The ValidationSummary helper method generates an unordered list (ul element) of validation
messages that are in the ModelStateDictionary object.

The ValidationSummary can be used to display all the error messages for all the fields. It can
also be used to display custom error messages. The following figure shows how
ValidationSummary displays the error messages.
ValidationSummary() Signature

MvcHtmlStringValidateMessage(bool excludePropertyErrors, string message, object


htmlAttributes)

Display field level error messages using ValidationSummary

By default, ValidationSummary filters out field level error messages. If you want to display field
level error messages as a summary then specify excludePropertyErrors = false.

Example - ValidationSummary to display field errors

@Html.ValidationSummary(false, "", new { @class = "text-danger" })

So now, the following Edit view will display error messages as a summary at the top. Please
make sure that you don't have a ValidationMessageFor method for each of the fields.
Learn more here - Understanding Validation In MVC - Part 4

27. What is Database First Approach in MVC using Entity Framework?

Answer

Database First Approach is an alternative to the Code First and Model First approaches to the
Entity Data Model which creates model codes (classes,properties, DbContextetc) from the
database in the project and that classes behaves as the link between database and controller.

There are the following approach which is used to connect with database to application.

 Database First
 Model First
 Code First

Database first is nothing but only a approach to create web application where database is
available first and can interact with the database. In this database, database is created first and
after that we manage the code. The Entity Framework is able to generate a business model
based on the tables and columns in a relational database.

Learn more here - Database First Approach With ASP.NET MVC Step By Step Part 1

28. What are the Folders in MVC application solutions?


Answer - Understanding the folders

When you create a project a folder structure gets created by default under the name of your
project which can be seen in solution explorer. Below i will give you a brief explanation of what
these folders are for.

Model

This folder contains classes that is used to provide data. These classes can contain data that is
retrived from the database or data inserted in the form by the user to update the database.

Controllers

These are the classes which will perform the action invoked by the user. These classes contains
methods known as "Actions" which responds to the user action accordingly.

Views

These are simple pages which uses the model class data to populate the HTML controls and
renders it to the client browser.

App_Start

Contains Classes such as FilterConfig, RoutesConfig, WebApiConfig. As of now we need to


understand the RouteConfig class. This class contains the default format of the url that should
be supplied in the browser to navigate to a specified page.

29. What is difference between MVC and Web Forms?

Answer - ASP.Net MVC / Web Forms difference


The following are some difference.

ASP.Net MVC ASP.Net Web Forms

View and logic are separate, it has separation of No separation of concerns; Views are
concerns theory. MVC 3 onwards has .aspx page as tightly coupled with logic (.aspx.cs /.vb
.cshtml. file).

Introduced concept of routing for route based URL. File-based routing .Redirection is based
Routing is declared in Global.asax for example. on pages.

Support Razor syntax as well as .aspx Support web forms syntax only.

State management handled via Tempdata, ViewBag,


and View Data. Since the controller and view are not State management handled via View
dependent and also since there is no view state State. Large viewstate, in other words
concept in ASP.NET, MVC keeps the pages increase in page size.
lightweight.

Partial Views User Controls

HTML Helpers Server Controls

Multiple pages can have the same controller to Each page has its own code, in other
satisfy their requirements. A controller may have words direct dependency on code. For
multiple Actions (method name inside the controller example Sachin.aspx is dependent on
class). Sachin.aspx.cs (code behind) file.

Unit Testing is quite easier than ASP.Net Web forms Direct dependency, tight coupling raises
Since a web form and code are separate files. issues in testing.

layouts Master pages

Here are more Similarities and Dissimilarities Between MVC and Web Forms.

30. What are the methods of handling an Error in MVC?

Answer
Exception handling may be required in any application, whether it is a web application or a
Windows Forms application.

ASP.Net MVC has an attribute called "HandleError" that provides built-in exception filters. The
HandleError attribute in ASP.NET MVC can be applied over the action method as well as
Controller or at the global level. The HandleError attribute is the default implementation of
IExceptionFilter. When we create a MVC application, the HandleError attribute is added within
the Global.asax.cs file and registered in the Application_Start event.

1. public static void RegisterGlobalFilters(GlobalFilterCollection f


ilters)
2. {
3. filters.Add(new HandleErrorAttribute());
4. }
5. protected void Application_Start()
6. {
7. AreaRegistration.RegisterAllAreas();
8. RegisterGlobalFilters(GlobalFilters.Filters);
9. RegisterRoutes(RouteTable.Routes);
10. }

Important properties of HandleError attribute

The HandleError Error attribute has a couple for properties that are very useful in handling the
exception.

ExceptionType

Type of exception to be catch. If this property is not specified then the HandleError filter handles
all exceptions.

View

Name of the view page for displaying the exception information.


Master

Master View for displaying the exception.

Order

Order in which the action filters are executed. The Order property has an integer value and it
specifies the priority from 1 to any positive integer value. 1 means highest priority and the
greater the value of the integer is, the lower is the priority of the filter.

AllowMultiple

It indicates whether more than one instance of the error filter attribute can be specified.

Example

1. [HandleError(View = "Error")]
2. public class HomeController: Controller
3. {
4. public ActionResult Index()
5. {
6. ViewBag.Message = "Welcome to ASP.NET MVC!";
7. int u = Convert.ToInt32(""); // Error line
8. return View();
9. }
10. }

HandleError Attribute at Action Method Level,

1. [HandleError(View = "Error")]
2. public ActionResult Index()
3. {
4. ViewBag.Message = "Welcome to ASP.NET MVC!";
5. int u = Convert.ToInt32(""); // Error line
6. return View();
7. }

Here are more details on Exception or Error Handling in ASP.Net MVC Using HandleError
Attribute.

31. How can we pass the data From Controller To View In MVC?

Answer

There are three options in Model View Controller (MVC) for passing data from controller to view.
This article attempts to explain the differences among ViewData, ViewBag and TempData with
examples. ViewData and ViewBag are similar and TempData performs additional responsibility.
The following are the key points on those three objects.

ViewData

 The ViewData is used to move data from controller to view.


 The ViewData is a dictionary of objects that are derived from the "ViewDataDictionary"
class and it will be accessible using strings as keys.
 ViewData contains a null value when redirection occurs.
 ViewData requires typecasting for complex data types.

ViewBag

 ViewBag is just a dynamic wrapper around ViewData and exists only in ASP.NET MVC
3. ViewBag is a dynamic property that takes advantage of the new dynamic features in
C# 4.0.
 ViewBag doesn't require typecasting for complex data types.
 ViewBag also contain a null value when redirection occurs.

TempData

 ViewData moves data from controller to view.


 Use TempData when you need data to be available for the next request, only. In the next
request, it will be there but will be gone after that.
 TempData is used to pass data from the current request to the subsequent request, in
other words in case of redirection. That means the value of TempData will not be null.

Learn more here - Various Ways to Pass Data From Controller to View in MVC 4
32. What is Scaffolding in MVC?

Answer

Scaffolding is a code generation framework for ASP.NET Web applications. Visual Studio 2013
includes pre-installed code generators for MVC and Web API projects. You add scaffolding to
your project when you want to quickly add code that interacts with data models. Using
scaffolding can reduce the amount of time to develop standard data operations in your project.

Prerequisites

To use ASP.NET Scaffolding, you must have,

 Microsoft Visual Studio 2013


 Web Developer Tools (part of default Visual Studio 2013 installation)
 ASP.NET Web Frameworks and Tools 2013 (part of default Visual Studio 2013
installation)

What are the Advantages of using Scaffolding ?

 Minimal or no code to create a data-driven Web applications.


 Quick development time.
 Pages that are fully functional and include display, insert, edit, delete, sorting, and
paging functionalities.
 Built-in data validation that is based on the database schema.
 Filters that are created for each foreign key or Boolean fields.

Learn more here - Scaffolding In MVC 5

33. What is ViewStart?

Answer

Razor View Engine introduced a new layout named _ViewStart which is applied on all view
automatically. Razor View Engine firstly executes the _ViewStart and then start rendering the
other view and merges them.
Example of Viewstart

1. @ {
2. Layout = "~/Views/Shared/_v1.cshtml";
3. } < !DOCTYPE html >
4. < html >
5. < head >
6. < meta name = "viewport"
7. content = "width=device-width" / >
8. < title > ViewStart < /title> < /head> < body >
9. < /body> < /html>

Learn more here - Viewstart Page in ASP.NET MVC 3

34. What is JsonResultType in MVC?

Answer

Action methods on controllers return JsonResult (JavaScript Object Notation result) that can be
used in an AJAX application. This class is inherited from the "ActionResult" abstract class. Here
Json is provided one argument which must be serializable. The JSON result object that
serializes the specified object to JSON format.

1. public JsonResult JsonResultTest()


2. {
3. return Json("Hello My Friend!");
4. }

Learn more here - ActionResult Return Type in MVC 3.0

35. What is TempData?

Answer - Tempdata

 TempData is a dictionary object derived from the TempDataDictionary class.


 TempData is used to pass data from the current request to a subsequent request, in
other words in the case of redirection.
 The life of a TempData is very short and it retains its value for a short period of time.
 It requires typecasting for complex data type as I’ve used in my example:
 @foreach (var item in
(List<MVCSample.Models.EmpRegistration>)TempData["EmployeeRegistration"])
 You can retain its value using the Keep method for subsequent requests.

36. How to use ViewBag?

Answer

ViewBag is dynamic property that takes advantage of new dynamic features in C# 4.0. It's also
used to pass data from a controller to a view. In short, The ViewBag property is simply a
wrapper around the ViewData that exposes the ViewData dictionary as a dynamic object. Now
create an action method "StudentSummary" in the "DisplayDataController" controller that stores
a Student class object in ViewBag.

1. public ActionResult StudentSummary()


2. {
3. var student = new Student()
4. {
5. Name = "Sandeep Singh Shekhawat",
6. Age = 24,
7. City = "Jaipur"
8. };
9. ViewBag.Student = student;
10. return View();
11. }
Thereafter create a view StudentSummary ("StudentSummary.cshtml") that shows student
object data. ViewBag does not require typecasting for complex data type so you can directly
access the data from ViewBag.

1. @ {
2. ViewBag.Title = "Student Summary";
3. var student = ViewBag.Student;
4. }
5. < table >
6. < tr >
7. < th > Name < /th> < th > Age < /th> < th > City < /th> < /tr
> < tr >
8. < td > @student.Name < /td> < td > @student.Age < /td> < td > @stud
ent.City < /td> < /tr>
9. < /table>

Here we used one more thing, "ViewBag.Title", that shows the title of the page.

Learn more here - Displaying Data on View From Controller

37. What are the Difference between ViewBag&ViewData?

Answer - Difference between ViewBag&ViewData?

 ViewData is a dictionary of objects that is derived from ViewDataDictionary class and


accessible using strings as keys.
 ViewBag is a dynamic property that takes advantage of the new dynamic features in C#
4.0.
 ViewData requires typecasting for complex data type and check for null values to avoid
error.
 ViewBag doesn't require typecasting for complex data type.
 Calling of ViewBag is:

ViewBag.Name = "Yogesh";

Calling of ViewDatais :
ViewData["Name"] = "yogesh";

Learn more here - Difference Between ViewBag & ViewData in MVC

38. What is Data Annotation Validator Attributes in MVC?

Answer - Using the Data Annotation Validator Attributes

DataAnnotation plays a vital role in added validation to properties while designing the model
itself. This validation can be added for both the client side and the server side.

You understand that decorating the properties in a model with an Attribute can make that
property eligible for Validation.

Some of the DataAnnotation used for validation are given below,

1. Required

Specify a property as required.


1. [Required(ErrorMessage="CustomerName is mandatory")]

2. RegularExpression

Specifies the regular expression to validate the value of the property.

1. [RegularExpression("[a-z]", ErrorMessage = "Invalid character")]

3. Range

Specifies the Range of values between which the property values are checked.

1. [Range(1000,10000,ErrorMessage="Range should be between 1k & 10k")]

4. StringLength

Specifies the Min & Max length for a string property.

1. [StringLength(50, MinimumLength = 5, ErrorMessage = "Minimum char is 5 and


maximum char is 10")]

5. MaxLength
Specifies the Max length for the property value.

1. [MaxLength(10,ErrorMessage="Customer Code is exceeding")]

6. MinLength

It is used to check for minimum length.

1. [MinLength(5, ErrorMessage = "Customer Code is too small")]

Learn more here - Adding Custom Validation in MVC

39. How can we done Custom Error Page in MVC?

Answer

The HandleErrorAttribute allows you to use a custom page for this error. First you need to
update your web.config file to allow your application to handle custom errors.

1. <system.web>
2. <customErrors mode="On">
3. </system.web>

Then, your action method needs to be marked with the atttribute.

1. [HandleError]
2. public class HomeController: Controller
3. {
4. [HandleError]
5. publicActionResultThrowException()
6. {
7. throw new ApplicationException();
8. }
9. }
By calling the ThrowException action, this would then redirect the user to the default error page.
In our case though, we want to use a custom error page and redirect the user there instead.So,
let's create our new custom view page.

Next, we simply need to update the HandleErrorAttribute on the action method.

1. [HandleError]
2. public class HomeController: Controller
3. {
4. [HandleError(View = "CustomErrorView")]
5. publicActionResultThrowException()
6. {
7. throw new ApplicationException();
8. }
9. }
Learn more here - Custom Error Page in ASP.NET MVC

40. Server Side Validation in MVC?

Answer

The ASP.NET MVC Framework validates any data passed to the controller action that is
executing, It populates a ModelState object with any validation failures that it finds and passes
that object to the controller. Then the controller actions can query the ModelState to discover
whether the request is valid and react accordingly.

I will use two approaches in this article to validate a model data. One is to manually add an error
to the ModelState object and another uses the Data Annotation API to validate the model data.

Approach 1 - Manually Add Error to ModelState object

I create a User class under the Models folder. The User class has two properties "Name" and
"Email". The "Name" field has required field validations while the "Email" field has Email
validation. So let's see the procedure to implement the validation. Create the User Model as in
the following,

1. namespace ServerValidation.Models
2. {
3. public class User
4. {
5. public string Name
6. {
7. get;
8. set;
9. }
10. public string Email
11. {
12. get;
13. set;
14. }
15. }
16. }
After that I create a controller action in User Controller (UserController.cs under Controllers
folder). That action method has logic for the required validation for Name and Email validation
on the Email field. I add an error message on ModelState with a key and that message will be
shown on the view whenever the data is not to be validated in the model.

1. using System.Text.RegularExpressions;
2. using System.Web.Mvc;
3. namespace ServerValidation.Controllers
4. {
5. public class UserController: Controller
6. {
7. public ActionResult Index()
8. {
9. return View();
10. }
11. [HttpPost]
12. public ActionResult Index(ServerValidation.Models.User mo
del)
13. {
14.
15. if (string.IsNullOrEmpty(model.Name))
16. {
17. ModelState.AddModelError("Name", "Name is re
quired");
18. }
19. if (!string.IsNullOrEmpty(model.Email))
20. {
21. string emailRegex = @ "^([a-zA-Z0-9_\-
\.]+)@((\[[0-9]{1,3}" +
22. @ "\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-
]+\" +
23. @ ".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
24. Regex re = new Regex(emailRegex);
25. if (!re.IsMatch(model.Email))
26. {
27. ModelState.AddModelError("Email", "Email
is not valid");
28. }
29. } else {
30. ModelState.AddModelError("Email", "Email is requi
red");
31. }
32. if (ModelState.IsValid)
33. {
34. ViewBag.Name = model.Name;
35. ViewBag.Email = model.Email;
36. }
37. return View(model);
38. }
39. }
40. }

Thereafter I create a view (Index.cshtml) for the user input under the User folder.

1. @model ServerValidation.Models.User
2. @ {
3. ViewBag.Title = "Index";
4. }
5. @using(Html.BeginForm())
6. {
7. if (@ViewData.ModelState.IsValid)
8. {
9. if (@ViewBag.Name != null)
10. { < b >
11. Name: @ViewBag.Name < br / >
12. Email: @ViewBag.Email < /b>
13. }
14. } < fieldset >
15. < legend > User < /legend> < div class = "editor-
label" >
16. @Html.LabelFor(model => model.Name) < /div> < div class =
"editor-field" >
17. @Html.EditorFor(model => model.Name)
18. @if(!ViewData.ModelState.IsValid)
19. {
20. < span class = "field-validation-
error" > @ViewData.ModelState["Name"].Errors[0].ErrorMessage < /span>

21.
22. }
23. < /div> < div class = "editor-label" >
24.
25. @Html.LabelFor(model => model.Email) < /div> < div class
= "editor-field" >
26. @Html.EditorFor(model => model.Email)
27. @if(!ViewData.ModelState.IsValid)
28. {
29. < span class = "field-validation-
error" > @ViewData.ModelState["Email"].Errors[0].ErrorMessage < /span>

30. }
31. < /div> < p >
32. < input type = "submit"
33. value = "Create" / >
34. < /p> < /fieldset>
35. }

41. What is the use of remote validation in MVC?

Answer

Remote validation is the process where we validate specific data posting data to a server
without posting the entire form data to the server. Let's see an actual scenario, in one of my
projects I had a requirement to validate an email address, whetehr it already exists in the
database. Remote validation was useful for that; without posting all the data we can validate
only the email address supplied by the user.

Practical Explanation

Let's create a MVC project and name it accordingly, for me its “TestingRemoteValidation”. Once
the project is created let's create a model named UserModel that will look like:

1. public class UserModel


2. {
3. [Required]
4. public string UserName
5. {
6. get;
7. set;
8. }
9. [Remote("CheckExistingEmail", "Home", ErrorMessage = "Email a
lready exists!")]
10. public string UserEmailAddress
11. {
12. get;
13. set;
14. }
15. }

Let's get some understanding of the remote attribute used, so the very first parameter
“CheckExistingEmail” is the the name of the action. The second parameter “Home” is referred to
as controller so to validate the input for the UserEmailAddress the “CheckExistingEmail” action
of the “Home” controller is called and the third parameter is the error message. Let's implement
the “CheckExistingEmail” action result in our home controller.
1. public ActionResult CheckExistingEmail(string UserEmailAddress)
2. {
3. bool ifEmailExist = false;
4. try
5. {
6. ifEmailExist = UserEmailAddress.Equals("mukeshknayak@gmail.com"
) ? true : false;
7. return Json(!ifEmailExist, JsonRequestBehavior.AllowGet);

8. } catch (Exception ex)


9. {
10. return Json(false, JsonRequestBehavior.AllowGet);
11. }
12. }

Learn more here - Remote Validation in MVC

42. What are the Exception filters in MVC?

Answer

Exception are part and parcel of an application. They are a boon and a ban for an application
too. Isn't it? This would be controversial, for developers it helps them track minor and major
defects in an application and sometimes they are frustrating when it lets users land on the
Yellow screen of death each time. This would make the users mundane to the application. Thus
to avoid this, developers handle the exceptions. But still sometimes there are a few unhandled
exceptions.

Now what is to be done for them? MVC provides us with built-in "Exception Filters" about which
we will explain here.
cc: Google

Let's start!

A Yellow screen of Death can be said is as a wardrobe malfunction of our application.

Get Started

Exception filters run when some of the exceptions are unhandled and thrown from an invoked
action. The reason for the exception can be anything and so is the source of the exception.

Creating an Exception Filter

Custom Exception Filters must implement the builtinIExceptionFilter interface. The interface
looks as in the following,

1. public interface IExceptionFilter


2. {
3. void OnException(ExceptionContext filterContext)
4. }
Whenever an unhandled exception is encountered, the OnException method gets invoked. The
parameter as we can see, ExceptionContext is derived from the ControllerContext and has a
number of built-in properties that can be used to get the information about the request causing
the exception. Their property's ExceptionContextpassess are shown in the following table:

Name Type Detail

Result ActionResult The result returned by the action being invoked.

The unhandled exceptions caused from the actions in the


Exception Exception
applications.

This is a very handy property that returns a bool value


ExceptionHandled BOOL (true/false) based on if the exception is handled by any of the
filters in the applicaiton or not.

The exception being thrown from the action is detailed by the Exception property and once
handled (if), then the property ExceptionHandled can be toggled, so that the other filters would
know if the exception has been already handled and cancel the other filter requests to handle.
The problem is that if the exceptions are not handled, then the default MVC behavior shows the
dreaded yellow screen of death. To the users, that makes a very impression on the users and
more importantly, it exposes the application's handy and secure information to the outside world
that may have hackers and then the application gets into the road to hell. Thus, the exceptions
need to be dealt with very carefully. Let's show one small custom exception filter. This filter can
be stored inside the Filters folder in the web project of the solution. Let's add a file/class called
CustomExceptionFilter.cs.

1. public class CustomExceptionFilter: FilterAttribute,


2. IExceptionFilter
3. {
4. public void OnException(ExceptionContext filterContext)
5. {
6. if (!filterContext.ExceptionHandled && filterContext.Except
ion is NullReferenceException)
7. {
8. filterContext.Result = new RedirectResult("customErrorP
age.html");
9. filterContext.ExceptionHandled = true;
10. }
11. }
12. }

Learn more here - Exception Filters in MVC


43. What is MVC HTML- Helpers and its Methods?

Answer

Helper methods are used to render HTML in the view. Helper methods generates HTML output
that is part of the view. They provide an advantage over using the HTML elements since they
can be reused across the views and also requires less coding. There are several builtin helper
methods that are used to generate the HTML for some commonly used HTML elements, like
form, checkbox, dropdownlist etc. Also we can create our own helper methods to generate
custom HTML. First we will see how to use the builtin helper methods and then we will see how
to create custom helper methods.

Standard HtmlHelper methods

Some of the standard helper methods are,

 ActionLink: Renders an anchor.


 BeginForm: Renders HTML form tag
 CheckBox: Renders check box.
 DropDownList: Renders drop-down list.
 Hidden: Renders hidden field
 ListBox: Renders list box.
 Password: Renders TextBox for password input
 RadioButton: Renders radio button.
 TextArea: Renders text area.
 TextBox: Renders text box.

Learn more here - HtmlHelper Methods in ASP.NET MVC

44. Define Controller in MVC?

Answer

The controller provides model data to the view, and interprets user actions such as button
clicks. The controller depends on the view and the model. In some cases, the controller and the
view are the same object.
The Controllers Folder

The Controllers Folder contains the controller classes responsible for handling user input and
responses. MVC requires the name of all controllers to end with "Controller".

In our example, Visual Web Developer has created the following files: HomeController.cs (for
the Home and About pages) and AccountController.cs (For the Log On pages):

Learn more here - ASP.Net MVC Controller

45. Explain Model in MVC?


Answer

The model represents the data, and does nothing else. The model does NOT depend on the
controller or the view. The MVC Model contains all application logic (business logic, validation
logic, and data access logic), except pure view and controller logic. With MVC, models both hold
and manipulate application data.

The Models Folde

The Models Folder contains the classes that represent the application model.

Visual Web Developer automatically creates an AccountModels.cs file that contains the models
for application security.

Learn more here - Model in ASP.Net MVC : Part 1

46. Explain View in MVC?

Answer

A view is responsible for displaying all of, or a portion of, data for users. In simple terms,
whatever we see on the output screen is a view.

The Views Folder

The Views folder stores the files (HTML files) related to the display of the application (the user
interfaces). These files may have the extensions html, asp, aspx, cshtml, and vbhtml, depending
on the language content.
The Views folder contains one folder for each controller. Visual Web Developer has created an
Account folder, a Home folder, and a Shared folder (inside the Views folder). The Account folder
contains pages for registering and logging in to user accounts. The Home folder is used for
storing application pages like the home page and the about page. The Shared folder is used to
store views shared between controllers (master pages and layout pages).

Learn more here - ASP.Net MVC View

47. What is Attribute Routing in MVC?

Answer

A route attribute is defined on top of an action method. The following is the example of a Route
Attribute in which routing is defined where the action method is defined.
In the following example, I am defining the route attribute on top of the action method

1. public class HomeController: Controller


2. {
3. //URL: /Mvctest
4. [Route(“Mvctest”)]
5. public ActionResult Index()
6. ViewBag.Message = "Welcome to ASP.NET MVC!";
7. return View();
8. }
9. }

Attribute Routing with Optional Parameter

We can also define an optional parameter in the URL pattern by defining a mark (“?") to the
route parameter. We can also define the default value by using parameter=value.

1. public class HomeController: Controller


2. {
3. // Optional URI Parameter
4. // URL: /Mvctest/
5. // URL: /Mvctest/0023654
6. [Route(“Mvctest /
7. {
8. customerName ?
9. }”)]
10. public ActionResult OtherTest(string customerName)
11. ViewBag.Message = "Welcome to ASP.NET MVC!";
12. return View();
13. }
14. // Optional URI Parameter with default value
15. // URL: /Mvctest/
16. // URL: /Mvctest/0023654
17. [Route(“Mvctest /
18. {
19. customerName = 0036952
20. }”)]
21. public ActionResult OtherTest(string customerName)
22. {
23. ViewBag.Message = "Welcome to ASP.NET MVC!";
24. return View();
25. }
26. }
Learn more here - Attribute Routing in ASP.Net MVC 5.0

48. Explain RenderSection in MVC?

Answer

RenderSection() is a method of the WebPageBase class. Scott wrote at one point, The first
parameter to the "RenderSection()" helper method specifies the name of the section we want to
render at that location in the layout template. The second parameter is optional, and allows us
to define whether the section we are rendering is required or not. If a section is "required", then
Razor will throw an error at runtime if that section is not implemented within a view template that
is based on the layout file (that can make it easier to track down content errors). It returns the
HTML content to render.

1. <div id="body">
2. @RenderSection("featured", required: false)
3. <section class="content-wrapper main-content clear-fix">
4. @RenderBody()
5. </section>
6. </div>

Learn more here - ASP.Net MVC 4 - Layout and Section in Razor

49. What is GET and POST Actions Types?

Answer

GET

GET is used to request data from a specified resource. With all the GET request we pass the
URL which is compulsory, however it can take the following overloads.

.get(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] ).done/.fail


POST

POST is used to submit data to be processed to a specified resource. With all the POST
requests we pass the URL which is compulsory and the data, however it can take the following
overloads.

.post(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

Learn more here - GET and POST Calls to Controller's Method in MVC

50. What's new in MVC 6?

Answer

In MVC 6 Microsoft removed the dependency of System.Web.Dll from MVC6 because it's so
expensive that typically it consume 30k of memory per request and response, whereas now
MVC 6 only requires 2k of memory per request and the response is a very small memory
consumtion.

The advantage of using the cloud-optimized framework is that we can include a copy of the
mono CLR with your website. For the sake of one website we do not need to upgrade the .NET
version on the entire machine. A different version of the CLR for a different website running side
by side.

MVC 6 is a part of ASP.NET 5 that has been designed for cloud-optimized applications. The
runtime automatically picks the correct version of the library when our MVC application is
deployed to the cloud.
The Core CLR is also supposed to be tuned with a high resource-efficient optimization.

Microsoft has made many MVC, Web API, WebPage and SignalLrpeices we call MVC 6.

Most of the problems are solved using the Roslyn Compiler. In ASP.NET vNext uses the Roslyn
Compiler. Using the Roslyn Compiler we do not need to compile the application, it automatically
compiles the application code. You will edit a code file and can then see the changes by
refreshing the browser without stopping or rebuilding the project.

Run on hosts other than IIS

Where we use MVC5 we can host it on an IIS server and we can also run it on top of an ASP.
NET Pipeline, on the other hand MVC 6 has a feature that makes it better and that feature is
itself hosted on an IIS server and a self-user pipeline.
Environment based configuration system

The configuration system provides an environment to easily deploy the application on the cloud.
Our application works just like a configuration provider. It helps to retrieve the value from the
various configuration sources like XML file.

MVC 6 includes a new environment-based configuration system. Unlike something else it


depends on just the Web.Config file in the previous version.

Dependency injection

Using the IServiceProvider interface we can easily add our own dependency injection container.
We can replace the default implementation with our own container.

1.Select the correct statement about Attributes used in C#.NET?A.The CLR can change the behaviour of
the code depending on attributes applied to it

B.If a bugFixAttribute is to recieve three paramteres, then the BugFixAttribute class should implement a
zero arguement constructor

C.To create a custom attribute we need to create a custom attribute structure and derive it from
System.Attribute

D.None of the mentioned

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option A

Explanation:

2.The correct way to apply the custom attribute called Employer which receives two arguements – name
of the employee and employeeid is?A.Custom attribute can be applied to an assembly
B.[assembly : Employer(“Ankit”,employeeid.one)].

C.[ Employer(“Ankit”, employeeid.second)] class employee{}

D.All of the mentioned

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option D

Explanation:

3.Which property among the following represents the current position of the stream?A.long Length

B.long Position

C.int Length

D.All of the mentioned

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option A

Explanation:

This property contains the length of the stream. This property is read-only.

4.Choose the file mode method which is used to create a new output file with the condition that the file
with same name must not exist.A.FileMode.CreateNew

B.FileMode.Create

C.FileMode.OpenOrCreate
D.FileMode.Truncate

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option A

Explanation:

Creates a new output file. The file must not already be existing.

5.Which method of character stream class returns the numbers of characters successfully read starting
at count?A.int Read()

B.int Read(char[] buffer, int index, int count)

C.int ReadBlock(char[ ] buffer, int index, int count)

D.None of the mentioned

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option B

Explanation:

Attempts to read the count characters into buffer starting at buffer[count], returning the number of
characters successfully read.

1. C# is a?
A. general-purpose programming language
B. object-oriented programming language
C. modern programming language
D. All of the above
View Answer
Ans : D

Explanation: C# is a modern, general-purpose, object-oriented programming language

2. C# developed by?
A. IBM
B. Google
C. Microsoft
D. Facebook
View Answer
Ans : C

Explanation: C# developed by Microsoft and approved by European Computer


Manufacturers Association (ECMA) and International Standards Organization (ISO).

3. CLI in C# Stands for?


A. Common Language Infrastructure
B. Code Language Infrastructure
C. Computer Language Infrastructure
D. C# Language Infrastructure
View Answer
Ans : A

Explanation: C# is designed for Common Language Infrastructure (CLI), which consists of


the executable code and runtime environment that allows use of various high-level
languages on different computer platforms and architectures.

4. C# has strong resemblance with?


A. C
B. C++
C. Java
D. Python
View Answer
Ans : C
Explanation: It has strong resemblance with Java, it has numerous strong programming
features that make it endearing to a number of programmers worldwide.

5. Which of the following not true about C#?


A. It is component oriented
B. It is a unstructured language
C. It is easy to learn
D. It is a part of .Net Framework.
View Answer
Ans : B

Explanation: C# is a structured language.

6. Choose .NET class name from which data type UInt is derived?
A. System.Int16
B. System.UInt32
C. System.UInt64
D. System.UInt16
View Answer
Ans : B

Explanation: By Definition class assigned to


i) System.Int16 = short.
ii) System.UInt32 = UInt.
iii) System.UInt64 = ULong.
iv) System.UInt16 = UShort.

7. The first line of the program is?


A. using System
B. namespace
C. using namespace
D. None of the above
View Answer
Ans : A

Explanation: The first line of the program using System; - the using keyword is used to
include the System namespace in the program. A program generally has multiple using
statements.
8. A namespace is a collection of classes.
A. TRUE
B. FALSE
C. Can be true or false
D. Can not say
View Answer
Ans : A

Explanation: A namespace is a collection of classes. The HelloWorldApplication namespace


contains the class HelloWorld.

9. In C#, Save the file using?


A. .c extension
B. .csharp extension
C. .net extension
D. .cs extension
View Answer
Ans : D

Explanation: Save the file as helloworld.cs

10. Number of digits upto which precision value of float data type is
valid?
A. Upto 6 digit
B. Upto 7 digit
C. Upto 8 digit
D. Upto 9 digit
View Answer
Ans : B

Explanation: Number of digits upto which precision value of float data type is valid is upto 7
digit
6.Which method among the following returns the integer if no character is available?A.int peek()

B.int read()

C.string ReadLine()
D.None of the mentioned

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option A

Explanation:

Obtains the next character from the input stream, but does not remove that character. Returns –1 if no
character is available.

7.Choose the output returned when read() reads the character from the console?A.String

B.Char

C.Integer

D.Boolean

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option C

Explanation:

Read() returns the character read from the console. It returns the result. The character is returned as an
int, which should be cast to char.

8.Select the method which returns the number of bytes from the array buffer:A.void WriteByte(byte
value)

B.int Write(byte[] buffer ,int offset ,int count)

C.write()
D.None of the mentioned

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option B

Explanation:

Writes a subrange of count bytes from the array buffer,beginning at buffer[offset], returning the
number of bytes written.

9.What is the output returned by Console if ReadLine() stores I/O error?A.1

B.0

C.False

D.I/O EXCEPTION ERROR

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option D

Explanation:

10.What will be the output of given code snippet?

static void Main(string[] args)

string h = "i lovelife";

string h1 = new string(h.Reverse().ToArray());


Console.WriteLine(h1);

Console.ReadLine();

A.efil evoli

B.lifelove i

C.efilevol i

D.efil evol i

View Answer

Workspace

Report

Discuss

Answer & Explanation

Answer: Option C

Explanation:

Reverse() an inbuilt method reverses all the characters singly and hence embed them into the string
completely.

Output :efilevol i

Question: 1

In C++ functions are also called ___

(A) Definitions

(B) Concepts

(C) Methods

(D) Organizers

View AnswerAns: C

Methods

Question: 2
Which of the following is not a valid class specifier?

(A) Private

(B) Pointer

(C) Public

(D) Protected

View AnswerAns: B

Pointer

Question: 3

OOP stands for ___

(A) Object to Object Programming

(B) Object Oriented Programming

(C) Online Objects Programming

(D) Object Oriented Processes

View AnswerAns: B

Object Oriented Programming

Question: 4

In a class data members are also called as ___

(A) Abstracts

(B) Attributes

(C) Properties

(D) Dimensions

View AnswerAns: B

Attributes

Question: 5

In C++, the class variables are called as ____


(A) Functions

(B) Constants

(C) Objects

(D) Methods

View AnswerAns: C

Objects

Select the correct implementation of the interface which is mentioned below.


interface a1

int fun(int i);

a. class a
{
int fun(int i) as a1.fu
{
}
}

b. class a: implements
{
int fun(int i)
{
}
}

c. class a: a1
{
int a1.fun(int i)
{
}
}

d. None of the mention

View Answer Report Discuss Too Difficult!

Answer: (c).class a: a1
{
int a1.fun(int i)
{
}
}

Q 1- Which of the following is a contextual keyword in C#?

A- get

B- set

C- add

D- All of the above.

Answer : D

Explanation

All of the above options are contextual keywords.

Show Answer

C# Online Quiz

Advertisements

Previous Page

Next Page

Following quiz provides Multiple Choice Questions (MCQs) related toC#. You will have to read all the
given answers and click over the correct answer. If you are not sure about the answer then you can
check the answer usingShow Answerbutton. You can useNext Quizbutton to check new set of questions
in the quiz.

Q 1- Which of the following is a contextual keyword in C#?

A- get

B- set
C- add

D- All of the above.

Answer : D

Explanation

All of the above options are contextual keywords.

Show Answer

Q 2- Which of the following is correct about Object Type in C#?

A- The Object Type is the ultimate base class for all data types in C# Common Type System (CTS).

B- Object is an alias for System.Object class.

C- The object types can be assigned values of any other types, value types, reference types, predefined
or user-defined types.

D- All of the above.

Answer : D

Explanation

All of the above options are correct.

Hide Answer

Q 3- Which of the following converts a type to a 32-bit integer in C#?

A- ToDecimal

B- ToDouble

C- ToInt16

D- ToInt32

Answer : D

Explanation

ToInt32() method converts a type to a 32-bit integer.

Show Answer

Q 4- Which of the following converts a type to an unsigned int type in C#?


A- ToType

B- ToUInt16

C- ToSingle

D- ToString

Answer : B

Explanation

ToUInt16() method converts a type to an unsigned int type.

Show Answer

Q 5- Which of the following statements is correct about access specifiers in C#?

A- Encapsulation is implemented by using access specifiers.

B- An access specifier defines the scope and visibility of a class member.

C- Both of the above.

D- None of the above.

Answer : C

Explanation

Both of the above statements are correct.

Hide Answer

Q 6- Which of the following is correct about params in C#?

A- By using the params keyword, a method parameter can be specified which takes a variable number of
arguments or even no argument.

B- Additional parameters are not permitted after the params keyword in a method declaration.

C- Only one params keyword is allowed in a method declaration.

D- All of the above.

Answer : D

Explanation

All of the above statements are correct.


Hide Answer

Q 7- Which of the following is the correct about class destructor?

A- A destructor is a special member function of a class that is executed whenever an object of its class
goes out of scope.

B- A destructor has exactly the same name as that of the class with a prefixed tilde (~) and it can neither
return a value nor can it take any parameters.

C- Both of the above.

D- None of the above.

Answer : C

Explanation

Both of the above options are correct.

Hide Answer

Q 8- The comparison operators can be overloaded.

A- true

B- false

Answer : A

Explanation

The comparison operators can be overloaded.

Hide Answer

Q 9- Which of the following preprocessor directive allows testing a symbol or symbols to see if they
evaluate to true in C#?

A- define

B- undef

C- if

D- elif

Answer : C

Explanation
#if − It allows tes ng a symbol or symbols to see if they evaluate to true.

Hide Answer

Q 10- Which of the following preprocessor directive lets you specify a block of code that you can expand
or collapse when using the outlining feature of the Visual Studio Code Editor in C#?

A- warning

B- region

C- line

D- error

Answer : B

C# Online Quiz

Advertisements

Previous Page

Next Page

Following quiz provides Multiple Choice Questions (MCQs) related toC#. You will have to read all the
given answers and click over the correct answer. If you are not sure about the answer then you can
check the answer usingShow Answerbutton. You can useNext Quizbutton to check new set of questions
in the quiz.

Q 1- We can use reserved keywords as identifiers in C# by prefixing them with @ character?

A- true

B- false

Answer : A

Explanation

if you want to use these keywords as identifiers, you may prefix the keyword with the @ character.
Hide Answer

Q 2- Which of the following is correct about dynamic Type in C#?

A- You can store any type of value in the dynamic data type variable.

B- Type checking for these types of variables takes place at run-time.

C- Both of the above.

D- None of the above.

Answer : C

Explanation

Both of the above options are correct.

Hide Answer

Q 3- Which of the following converts a type to a 32-bit integer in C#?

A- ToDecimal

B- ToDouble

C- ToInt16

D- ToInt32

Answer : D

Explanation

ToInt32() method converts a type to a 32-bit integer.

Hide Answer

Q 4- Which of the following converts a type to an unsigned int type in C#?

A- ToType

B- ToUInt16

C- ToSingle

D- ToString

Answer : B
Explanation

ToUInt16() method converts a type to an unsigned int type.

Show Answer

Q 5- Which of the following access specifier in C# allows a child class to access the member variables and
member functions of its base class?

A- Public

B- Private

C- Protected

D- Internal

Answer : C

Explanation

Protected access specifier allows a child class to access the member variables and member functions of
its base class.

Show Answer

Q 6- Which of the following is true about C# structures?

A- Structures can have methods, fields, indexers, properties, operator methods, and events.

B- Structures can have defined constructors, but not destructors.

C- You cannot define a default constructor for a structure. The default constructor is automatically
defined and cannot be changed.

D- All of the above.

Answer : D

Explanation

All of the above options are correct.

Hide Answer

Q 7- Which of the following is true about C# structures vs C# classes?

A- Classes are reference types and structs are value types.

B- Structures do not support inheritance.


C- Structures cannot have default constructor

D- All of the above.

Answer : D

Explanation

All of the above options are correct.

Show Answer

Q 8- Function overloading is a kind of static polymorphism.

A- true

B- false

Answer : A

Explanation

Function overloading is a kind of static polymorphism.

Hide Answer

Q 9- Which of the following preprocessor directive allows you to undefine a symbol in C#?

A- define

B- undef

C- region

D- endregion

Answer : B

Explanation

#undef: It allows you to undefine a symbol.

Hide Answer

Q 10- The System.SystemException class is the base class for all predefined system exception in C#?

A- true

B- false
Answer : A

Explanation

The System.SystemException class is the base class for all predefined system exception.

Question: 6

Private access specifier is accessible by special function called ____

(A) Void

(B) Inline

(C) Friend

(D) All of these

View AnswerAns: C

Friend

Question: 7

_____ member variable are initialized only once when the first object of its class is created.

(A) Inline

(B) Static

(C) Private

(D) Public

View AnswerAns: B

Static

Question: 8

One copy of ___ data members of a class are shared by all objects of that class.

(A) Public

(B) Static

(C) Private

(D) Inline
View AnswerAns: B

Static

Question: 9

The members defined within the class behave like ____functions.

(A) Inline

(B) Public

(C) Friend

(D) None of these

View AnswerAns: A

Inline

Question: 10

:: is a ___

(A) Short circuit AND

(B) Short circuit OR

(C) Not operator

(D) Scope resolution operator

View AnswerAns: D

Scope resolution operator

1. The capability of an object in Csharp to take number of different forms and hence display
behaviour as according is known as ___________
a) Encapsulation
b) Polymorphism
c) Abstraction
d) None of the mentioned
View Answer
Answer: b
Explanation: None.

2. What will be the output of the following C# code?

1. public class sample


2. {
3. public static int x = 100;
4. public static int y = 150;
5.
6. }
7. public class newspaper :sample
8. {
9. new public static int x = 1000;
10. static void Main(string[] args)
11. {
12. console.writeline(sample.x + " " + sample.y + " " +
x);
13. }
14. }

a) 100 150 1000


b) 1000 150 1000
c) 100 150 1000
d) 100 150 100
View Answer
Answer: c
Explanation: sample.x = 100
sample.y = 150
variable within scope of main() is x = 1000
Output :
100 150 1000

3. Which of the following keyword is used to change data and behavior of a base class by
replacing a member of the base class with a new derived member?
a) Overloads
b) Overrides
c) new
d) base
View Answer
Answer: c
Explanation: None.

4. Correct way to overload +operator?


a) public sample operator + (sample a, sample b)
b) public abstract operator + (sample a,sample b)
c) public static sample operator + (sample a, sample b)
d) all of the mentioned
View Answer
Answer: d
Explanation: None.
advertisement

5. What will be the Correct statement of the following C# code?

1. public class maths


2. {
3. public int x;
4. public virtual void a()
5. {
6.
7. }
8.
9. }
10. public class subject : maths
11. {
12. new public void a()
13. {
14.
15. }
16.
17. }

a) The subject class version of a() method gets called using sample class reference which
holds subject class object
b) subject class hides a() method of base class
c) The code replaces the subject class version of a() with its math class version
d) None of the mentioned
View Answer
Answer: d
Explanation: None.

6. Select the sequence of execution of function f1(), f2() & f3() in C# .NET CODE?

1. class base
2. {
3. public void f1() {}
4. public virtual void f2() {}
5. public virtual void f3() {}
6. }
7. class derived :base
8. {
9. new public void f1() {}
10. public override void f2() {}
11. public new void f3() {}
12. }
13. class Program
14. {
15. static void Main(string[] args)
16. {
17. baseclass b = new derived();
18. b.f1 ();
19. b.f2 ();
20. b.f3 ();
21. }
22. }

a)

f1() of derived class get executed

f2() of derived class get executed


f3() of base class get executed

b)

f1() of base class get executed

f2() of derived class get executed

f3() of base class get executed

c)

f1() of base class get executed

f2() of derived class get executed

f3() of derived class get executed

d)

f1() of derived class get executed

f2() of base class get executed

f3() of base class get executed

View Answer
Answer: b
Explanation: None.

7. Which of the following statements is correct?


a) Each derived class does not have its own version of a virtual method
b) If a derived class does not have its own version of virtual method then one in base class is
used
c) By default methods are virtual
d) All of the mentioned
View Answer
Answer: c
Explanation: None.

8. Correct code to be added for overloaded operator – for the following C# code?
1. class csharp
2. {
3. int x, y, z;
4. public csharp()
5. {
6.
7. }
8. public csharp(int a ,int b ,int c)
9. {
10. x = a;
11. y = b;
12. z = c;
13. }
14. Add correct set of code here
15. public void display()
16. {
17. console.writeline(x + " " + y + " " + z);
18. }
19. class program
20. {
21. static void Main(String[] args)
22. {
23. csharp s1 = new csharp(5 ,6 ,8);
24. csharp s3 = new csharp();
25. s3 = - s1;
26. s3.display();
27. }
28. }
29. }

a)

1. public static csharp operator -(csharp s1)


2. {
3. csharp t = new csharp();
4. t.x = s1.x;
5. t.y = s1.y;
6. t.z = -s1.z;
7. return t;
8. }

b)

1. public static csharp operator -(csharp s1)


2. {
3. csharp t = new csharp();
4. t.x = s1.x;
5. t.y = s1.y;
6. t.z = s1.z;
7. return t;
8. }

c)

1. public static csharp operator -(csharp s1)


2. {
3. csharp t = new csharp();
4. t.x = -s1.x;
5. t.y = -s1.y;
6. t.z = -s1.z;
7. return t;
8. }

d) None of the mentioned


View Answer
Answer: c
Explanation: None.

9. Selecting appropriate method out of number of overloaded methods by matching


arguments in terms of number, type and order and binding that selected method to object at
compile time is called?
a) Static binding
b) Static Linking
c) Compile time polymorphism
d) All of the mentioned
View Answer
Answer: d
Explanation: None.

10. Wrong statement about run time polymorphism is?


a) The overridden base method should be virtual, abstract or override
b) An abstract method is implicitly a virtual method
c) An abstract inherited property cannot be overridden in a derived class
d) Both override method and virtual method must have same access level modifier
View Answer
Answer: c
Explanation: None.

41. Select the namespace/namespaces which consists of methods like Length(), Indexer(), Append() for manipula
strings.

a. System.Class

b. System.Array

c. System.Text

d. None of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (c).System.Text
42. Select the method used to write single byte to a file?

a. Write()

b. Wrteline()

c. WriteByte()

d. All of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (c).WriteByte()

43. Select the namespace on which the stream classes are defined?

a. System.IO

b. System.Input

c. System.Output

d. All of the mentioned

View Answer Report Discuss Too Difficult!

44. Choose the class on which all stream classes are defined?

a. System.IO.stream

b. Sytem.Input.stream

c. System.Output.stream

d. All of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (a).System.IO.stream
45. Choose the stream class method which is used to close the connection:

a. close()

b. static close()

c. void close()

d. none of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (c).void close()

46. The method used to write a single byte to an output stream?

a. void WriteByte(byte value)

b. int Write(byte[] buffer ,int offset ,int count)

c. write()

d. none of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (a).void WriteByte(byte value)

47. Select the method which writes the contents of the stream to the physical device.

a. fflush()

b. void fflush()

c. void Flush()

d. flush()

View Answer Report Discuss Too Difficult!

Answer: (c).void Flush()


48. Select the method which returns the number of bytes from the array buffer:

a. void WriteByte(byte value)

b. int Write(byte[] buffer ,int offset ,int count)

c. write()

d. none of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (b).int Write(byte[] buffer ,int offset ,int count)

49. Name the method which returns integer as -1 when the end of file is encountered.

a. int read()

b. int ReadByte()

c. void readbyte()

d. none of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (b).int ReadByte()

50. Select the statements which define the stream.

a. A stream is an abstraction that produces or consumes information

b. A stream is linked to a physical device by the I/0 system

c. C# programs perform I/O through streams

d. All of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (d).All of the mentioned

1. Which of the following cannot further inspect the attribute that is once ap
a. Linker

b. ASP.NET Runtime

c. Language compilers

d. CLR

View Answer Report Discuss Too Difficult!

Answer: (a).Linker

2. To apply an attribute to an Assembly, the correct way of implementation is?

a. [AssemblyInfo: AssemblyDescription (“Csharp”)].

b. [assembly: AssemblyDescription(“Csharp”)].

c. [AssemblyDescription(“Csharp”)].

d. (Assembly:AssemblyDescription(“Csharp”)].

View Answer Report Discuss Too Difficult!

Answer: (b).[assembly: AssemblyDescription(“Csharp”)].

3. The correct method to pass parameter to an attribute is?

a. By name

b. By address

c. By value

d. By reference

View Answer Report Discuss Too Difficult!

Answer: (a).By name

4. Which among the following is the correct form of applying an attribute?


a. <Serializable()>class sample
{

b. (Serializable())class sample
{

c. [Serializable()] class sample


{

d. None of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (c).[Serializable()] class sample


{

5. Which among the following cannot be a target for a custom attribute?

a. Enum

b. Event

c. Interface

d. Namespace

View Answer Report Discuss Too Difficult!

Answer: (d).Namespace

6. Select the correct statement about Attributes used in C#.NET?

a. The CLR can change the behaviour of the code depending on attributes applied to it

b. If a bugFixAttribute is to recieve three paramteres, then the BugFixAttribute class should implement a zero arg
constructor
c. To create a custom attribute we need to create a custom attribute structure and derive it from System.Attribute

d. None of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (a).The CLR can change the behaviour of the code depending on attributes applied to it

7. The correct way to apply the custom attribute called Employer which receives two arguements – name of the
employee and employeeid is?

a. Custom attribute can be applied to an assembly

b. [assembly : Employer(“Ankit”,employeeid.one)].

c. [ Employer(“Ankit”, employeeid.second)] class employee


{
}

d. All of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (d).All of the mentioned

8. Which of the following is the correct statement about inspecting an attribute in C#.NET?

a. An attribute can be inspected at link time

b. An attribute can be inspected at design time

c. An attribute can be inspected at run time

d. None of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (a).An attribute can be inspected at link time

9. Attributes could be applied to


a. Method

b. Class

c. Assembly

d. All of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (d).All of the mentioned

10. The [Serializable()] attributes gets inspected at:

a. compile time

b. run time

c. design time

d. linking time

View Answer Report Discuss Too Difficult!

Answer: (b).run time


A Dynamic Link library (DLL) is a library that contains functions and codes that can be used by
more than one program at a time. Once we have created a DLL file, we can use it in many
applications. The only thing we need to do is to add the reference/import the DLL File. Both DLL
and .exe files are executable program modules but the difference is that we cannot execute DLL
files directly.

Creating DLL File

Step 1 - Open Visual Studio then select "File" -> "New" -> "Project..." then seelct "Visual C#" ->
"Class library".
(I give it the name "Calculation".)

Step 2 - Change the class name ("class1.cs") to "calculate.cs".

Step 3 - In the calculate class, write methods for the addition and subtraction of two integers (for
example purposes).
Step 4 - Build the solution (F6). If the build is successful then you will see a "calculation.dll" file
in the "bin/debug" directory of your project.

We have created our DLL file. Now we will use it in another application.

Using DLL File

Step 1 - Open Visual Studio then select "File" -> "New" -> "Project..." then select "Visual C#" ->
"Windows Forms application".

Step 2 - Design the form as in the following image:


Step 3 - Add a reference for the dll file, "calculation.dll", that we created earlier. Right-click on
the project and then click on "Add reference".

Step 4 - Select the DLL file and add it to the project.


After adding the file, you will see that the calculation namespace has been added (in
references) as in the following:

Step 5 - Add the namespace ("using calculation;") as in the following:


Step 6

1. using System;
2. using System.Collections.Generic;
3. using System.ComponentModel;
4. using System.Data;
5. using System.Drawing;
6. using System.Linq;
7. using System.Text;
8. using System.Windows.Forms;
9. using Calculation;
10.
11. namespace MiniCalculator
12. {
13. public partial class Form1 : Form
14. {
15.
16. public Form1()
17. {
18. InitializeComponent();
19. }
20. calculate cal = new calculate();
21. //Addition Button click event
22. private void button1_Click(object sender, EventArgs e)
23. {
24. try
25. {
26. //storing the result in int i
27. int i = cal.Add(int.Parse(txtFirstNo.Text),
int.Parse(txtSecNo.Text));
28. txtResult.Text = i.ToString();
29. }
30.
31. catch (Exception ex)
32. {
33. MessageBox.Show(ex.Message);
34. }
35. }
36.
37. //Subtraction button click event
38.
39. private void button2_Click(object sender, EventArgs
e)
40. {
41. Try
42. {
43. //storing the result in int i
44. int i = cal.Sub(int.Parse(txtFirstNo.Text), int.P
arse(txtSecNo.Text));
45. txtResult.Text = i.ToString();
46. }
47. catch (Exception ex)
48. {
49. MessageBox.Show(ex.Message);
50. }
51. }
52. }
53. }

54. 11. Which of the classes provide the operation of reading from and writing to the console in C#.NET?

a. System.Array

b. System.Output

c. System.ReadLine

d. System.Console

View Answer Report Discuss Too Difficult!

Answer: (d).System.Console
12. Which of the given stream methods provide access to the output console by default in C#.NET?

a. Console.In

b. Console.Out

c. Console.Error

d. All of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (b).Console.Out

13. Which of the given stream methods provide the access to the input console in C#.NET?

a. Console.Out

b. Console.Error

c. Console.In

d. All of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (c).Console.In

14. The number of input methods defined by the stream method Console.In in C#.NET is?

a. 4

b. 3

c. 2

d. 1

View Answer Report Discuss Too Difficult!

Answer: (b).3
15. Select the correct methodS provided by Console.In?

a. Read(), ReadLine()

b. ReadKey(), ReadLine()

c. Read(), ReadLine(), ReadKey()

d. ReadKey(), ReadLine()

View Answer Report Discuss Too Difficult!

Answer: (c).Read(), ReadLine(), ReadKey()

16. Choose the output returned when read() reads the character from the console?

a. String

b. Char

c. Integer

d. Boolean

View Answer Report Discuss Too Difficult!

Answer: (c).Integer

17. Choose the output returned when error condition is generated while read() reads from the console.

a. False

b. 0

c. -1

d. All of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (c).-1
18. Choose the object of TextReader class.

a. Console.In

b. Console.Out

c. Console.Error

d. None of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (a).Console.In

19. Choose the object/objects defined by the Textwriter class.

a. Console.In

b. Console

c. Console.Error

d. None of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (c).Console.Error

20. Choose the output for the given set of code:


static void Main(string[] args)

int a = 10, b = 0;

int result;

Console.Out.WriteLine("This will generate an exception.");

try
{

result = a / b; // generate an exception

catch (DivideByZeroException exc)

Console.Error.WriteLine(exc.Message);

Console.ReadLine();

a. This will generate an exception

b. 0

c. Compile time error

d. This will generate an exception


Attempted to Divide by Zero

View Answer Report Discuss Too Difficult!

Answer: (a).This will generate an exception

21. Choose the methods provided by Console.Out and Console.Error?

a. Write

b. WriteLine

c. WriteKey

d. Write & WriteLine

View Answer Report Discuss Too Difficult!

Answer: (d).Write & WriteLine


22. Choose the output for the following set of code?
static void Main(string[] args)

Console.WriteLine("This is a Console Application:");

Console.Write("Please enter your lucky number:");

string val1 = Console.ReadLine();

int val2 = System.Convert.ToInt32(val1, 10);

val2 = val2 * val2;

Console.WriteLine("square of number is:" +val2);

Console.Read();

a. Compile time error

b. Runs successfully does not print anything

c. Runs successfully, ask for input and hence displays the result

d. Syntax Error

View Answer Report Discuss Too Difficult!

Answer: (c).Runs successfully, ask for input and hence displays the result

23. Name the exception thrown by read() on failure.

a. InterruptedException

b. SystemException

c. SystemInputException

d. I/O Exception

View Answer Report Discuss Too Difficult!


Answer: (d).I/O Exception

24. Which of these methods are used to read single character from the console?

a. get()

b. getline()

c. read()

d. readLine()

View Answer Report Discuss Too Difficult!

Answer: (c).read()

25. Which of these method used to read strings from the console?

a. get()

b. getline()

c. read()

d. readLine()

View Answer Report Discuss Too Difficult!

Answer: (d).readLine()

26. Which among the following methods are used to write characters to a string?

a. StreamWriter

b. StreamReader

c. StringWriter

d. None of the mentioned

View Answer Report Discuss Too Difficult!


Answer: (c).StringWriter

27. Which method in Console enables to read individual inputs directly from the keyboard in a non line buffered m

a. Read()

b. ReadKey()

c. ReadLine()

d. All of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (b).ReadKey()

28. What is the output returned by Console if ReadLine() stores I/O error?

a. 1

b. 0

c. False

d. I/O EXCEPTION ERROR

View Answer Report Discuss Too Difficult!

Answer: (d).I/O EXCEPTION ERROR

29. What would be the output for following input from the console as a character?
static void Main(string[] args)

Console.WriteLine("what is your name?");

char s;
s = Convert.ToChar(Console.ReadLine());

Console.WriteLine("how are you: "+s);

Console.Read();

a. Compile time error

b. Code run successfully prints nothing on console

c. Code runs successfully prints input on console

d. Run time error

View Answer Report Discuss Too Difficult!

Answer: (d).Run time error

30. Name the method/methods used to read byte streams from the file?

a. ReadByte()

b. Read

c. Readkey()

d. None of the mentioned

View Answer Report Discuss Too Difficult!

Answer: (a).ReadByte()
Question: 1

A class belongs to which of the following data types?

(A) Array Type

(B) Derived Type

(C) Built-in Type

(D) User Defined Type

View AnswerAns: D
User Defined Type

Question: 2

Every class declaration is terminated by ____

(A) ,(comma)

(B) .(dot)

(C) ; (semi colon)

(D) :: (double colon)

View AnswerAns: C

; (semi colon)

Question: 3

A member function calling another function directly is called as ____

(A) Nesting functions

(B) Recursive functions

(C) Inline functions

(D) Friend functions

View AnswerAns: A

Nesting functions

Question: 4

Class access specifiers are also known as ____

(A) Specifications

(B) Class depth

(C) Visibility labels

(D) None of these

View AnswerAns: C

Visibility labels

Question: 5

____ are the functions that perform specific task in a class.

(A) Data functions


(B) Concrete functions

(C) Member functions

(D) Data members

View AnswerAns: C

Member functions

Question: 6

The class body has ___ access specifies.

(A) 1

(B) 2

(C) 3

(D) 4

View AnswerAns: C

Question: 7

The members declared as ____ can only be accessed within the class.

(A) Private

(B) Public

(C) Protected

(D) Class

View AnswerAns: A

Private

Question: 8

Class comprises ____

(A) Data members

(B) Member functions

(C) Both (a) and (b)

(D) None of these

View AnswerAns: C
Both (a) and (b)

Question: 9

When objects of a class are created, separate memory is allocated for?

(A) Member functions only

(B) Member variables only

(C) Both a and b

(D) Neither functions nor variables

View AnswerAns: B

Member variables only

Question: 10

The class access specifier used to access friend function is ____

(A) Private

(B) Public

(C) Protected

(D) Both (b) and (c)

View AnswerAns: B

Public

Question: 1

The members of a class are accessed using ___

(A) New operator

(B) Dot operator

(C) + operator

(D) Size of operator

View AnswerAns: B

Dot operator

Question: 2

The body of a class is terminated by a _____

(A) .
(B) ;

(C) :

(D) #

View AnswerAns: B

Question: 3

By default class members are treated as ____

(A) Public

(B) Private

(C) Protected

(D) Unprotected

View AnswerAns: D

Unprotected

Question: 4

The binding of data and functions together into a single entity is known as ____

(A) Inheritance

(B) Encapsulation

(C) Overloading

(D) Polymorphism

View AnswerAns: B

Encapsulation

Question: 5

Which of the following is a way to bind the data and its associated functions together?

(A) Methods

(B) Class

(C) Data

(D) Functions

View AnswerAns: B
Class

Question: 6

Which of the following is a user defined data type?

(A) Protected

(B) Public

(C) Object

(D) Class

View AnswerAns: D

Class

Question: 7

The lifetime of a static member variable is same as ___

(A) Lifetime of the program

(B) The public variable of any object

(C) The private of variable of any object

(D) The first object of its class

View AnswerAns: A

Lifetime of the program

Question: 8

Which one of the following language features classes?

(A) C

(B) C++

(C) Basic

(D) None

View AnswerAns: B

C++

Question: 9

The return type of a member function of a class can be ____

(A) A valid C++ data type or object data type


(B) Only a valid C++ data type

(C) Only object data type

(D) None of the given

View AnswerAns: A

A valid C++ data type or object data type

Question: 10

A language based on graphics for use in education is

(A) Logo

(B) COBOL

(C) BASIC

(D) PROLOG

View AnswerAns: A

Logo

Question: 1

Bjarne Stroustrup initially named C++ as

(A) C with classes

(B) Advanced C

(C) Deep C

(D) D

View AnswerAns: A

C with classes

Question: 2

Which of the following statements in NOT true?

(A) A non member function cannot access the private data of a class

(B) The return type of a member function cannot be object data type

(C) Several different classes can use the same function name

(D) Member functions can be of static type

View AnswerAns: D
Member functions can be of static type

Question: 3

int ex:: output ()

Which of the following is true with reference to the above line?

(A) The function output returns integer data type

(B) The function output returns ex type of data

(C) The class output returns integer type of data

(D) The function ex returns integer type of data

View AnswerAns: A

The function output returns integer data type

Question: 4

The body of the class starts and ends with

(A) Braces i.e.., {}

(B) Semi colon(;)

(C) Start and stop

(D) Begin and end

View AnswerAns: A

Braces i.e.., {}

Question: 5

Data abstraction in C++ is achieved by

(A) Encapsulation()

(B) Data Hiding()

(C) Polymorphism()

(D) Inheritance()

View AnswerAns: B

Data Hiding()

Question: 6

_____ of a class are data variables that represent the features or properties of a class.
(A) Access specifiers

(B) Visibility labels

(C) Member functions

(D) Data members

View AnswerAns: D

Data members

Question: 7

Declaration and function definitions are two specifications of which of the following

(A) Comments

(B) Class

(C) Data type

(D) None of the given

View AnswerAns: B

Class

Question: 8

The members that can also be accessed from outside the class should be declared as

(A) Protected

(B) Private

(C) Public

(D) None of these

View AnswerAns: C

Public

Question: 9

Members of a class are classified as

(A) Data functions and member functions

(B) Data hiding and data abstraction

(C) Data variables and data hiding

(D) Data members and member function


View AnswerAns: D

Data members and member function

Question: 10

void sum:: input ()

The above line tells

(A) function input is sub function of sum

(B) function sum is sub function of input

(C) function input is declared within the class sum

(D) function sum is declared within the class input

View AnswerAns: C

function input is declared within the class sum

Question: 11

Data hiding refers to _____

(A) not giving names to data

(B) not specifying members and functions of a class

(C) declaring members as public

(D) members and functions of a class are not accessible by members of outside class

View AnswerAns: D

members and functions of a class are not accessible by members of outside class

Question: 12

The class members declared _____ can be accessed only within the class and the members
of the inherited classes.

(A) protected

(B) unprotected

(C) public

(D) private

View AnswerAns: A

protected
Question: 13

Declaration of class member are declared as private can be accessed only

(A) separately in another class

(B) inside or outside the class

(C) outside the class

(D) within class

View AnswerAns: D

within class

Question: 14

The private data of a class can be accessed

(A) only by member functions of its own class and friend functions

(B) only by member functions of its own class

(C) only by friend functions

(D) by any function

View AnswerAns: A

only by member functions of its own class and friend functions

Question: 15

The member functions declared under which scope can be accessed by the objects.

(A) protected

(B) global

(C) private

(D) public

View AnswerAns: C

private

1. Which among the following best describes encapsulation?


a) It is a way of combining various data members into a single unit
b) It is a way of combining various member functions into a single unit
c) It is a way of combining various data members and member functions into a single unit
which can operate on any data
d) It is a way of combining various data members and member functions that operate on those
data members into a single unit
View Answer
Answer: d
Explanation: It is a way of combining both data members and member functions, which
operate on those data members, into a single unit. We call it a class in OOP generally. This
feature have helped us modify the structures used in C language to be upgraded into class
in C++ and other languages.

2. If data members are private, what can we do to access them from the class object?
a) Create public member functions to access those data members
b) Create private member functions to access those data members
c) Create protected member functions to access those data members
d) Private data members can never be accessed from outside the class
View Answer
Answer: a
Explanation: We can define public member functions to access those private data members
and get their value for use or alteration. They can’t be accessed directly but is possible to be
access using member functions. This is done to ensure that the private data doesn’t get
modified accidentally.

3. While using encapsulation, which among the following is possible?


a) Code modification can be additional overhead
b) Data member’s data type can be changed without changing any other code
c) Data member’s type can’t be changed, or whole code have to be changed
d) Member functions can be used to change the data type of data members
View Answer
Answer: b
Explanation: Data member’s data type can be changed without changing any further code.
All the members using that data can continue in the same way without any modification.
Member functions can never change the data type of same class data members.

4. Which feature can be implemented using encapsulation?


a) Inheritance
b) Abstraction
c) Polymorphism
d) Overloading
View Answer
Answer: b
Explanation: Data abstraction can be achieved by using encapsulation. We can hide the
operation and structure of actual program from the user and can show only required
information by the user.

5. Find which of the following uses encapsulation?


a) void main(){ int a; void fun( int a=10; cout<<a); fun(); }
b) class student{ int a; public: int b;};
c) class student{int a; public: void disp(){ cout<<a;} };
d) struct topper{ char name[10]; public : int marks; }
View Answer
Answer: c
Explanation: It is the class which uses both the data members and member functions being
declared inside a single unit. Only data members can be there in structures also. And the
encapsulation can only be illustrated if some data/operations are associated within class.
advertisement

6. Encapsulation helps in writing ___________ classes in java.


a) Mutable
b) Abstract
c) Wrapper
d) Immutable
View Answer
Answer: d
Explanation: Immutable classes are used for caching purpose generally. And it can be
created by making the class as final and making all its members private.

7. Which among the following should be encapsulated?


a) The data which is prone to change is near future
b) The data prone to change in long terms
c) The data which is intended to be changed
d) The data which belongs to some other class
View Answer
Answer: a
Explanation: The data prone to change in near future is usually encapsulated so that it doesn’t
get changed accidentally. We encapsulate the data to hide the critical working of program
from outside world.

8. How can Encapsulation be achieved?


a) Using Access Specifiers
b) Using only private members
c) Using inheritance
d) Using Abstraction
View Answer
Answer: a
Explanation: Using access specifiers we can achieve encapsulation. Using this we can in turn
implement data abstraction. It’s not necessary that we only use private access.

9. Which among the following violates the principle of encapsulation almost always?
a) Local variables
b) Global variables
c) Public variables
d) Array variables
View Answer
Answer: b
Explanation: Global variables almost always violates the principles of encapsulation.
Encapsulation says the data should be accessed only by required set of elements. But global
variable is accessible everywhere, also it is most prone to changes. It doesn’t hide the internal
working of program.
10. Which among the following would destroy the encapsulation mechanism if it was allowed
in programming?
a) Using access declaration for private members of base class
b) Using access declaration for public members of base class
c) Using access declaration for local variable of main() function
d) Using access declaration for global variables
View Answer
Answer: a
Explanation: If using access declaration for private members of base class was allowed in
programming, it would have destroyed whole concept of encapsulation. As if it was possible,
any class which gets inherited privately, would have been able to inherit the private members
of base class, and hence could access each and every member of base class.

11. Which among the following can be a concept against encapsulation rules?
a) Using function pointers
b) Using char* string pointer to be passed to non-member function
c) Using object array
d) Using any kind of pointer/array address in passing to another function
View Answer
Answer: d
Explanation: If we use any kind of array or pointer as data member which should not be
changed, but in some case its address is passed to some other function or similar variable.
There are chances to modify its whole data easily. Hence Against encapsulation.

12. Consider the following code and select the correct option.

class student
{
int marks;
public : int* fun()
{
return &marks;
}
};
main()
{
student s;
int *ptr=c.fun();
return 0;
}

a) This code is good to go


b) This code may result in undesirable conditions
c) This code will generate error
d) This code violates encapsulation
View Answer
Answer: d
Explanation: This code violates the encapsulation. By this code we can get the address of
the private member of the class, hence we can change the value of private member, which is
against the rules.
13. Consider the code and select the wrong choice.

class hero
{
char name[10];
public : void disp()
{
cout<<name;
}
};

a) This maintains encapsulation


b) This code doesn’t maintain encapsulation
c) This code is vulnerable
d) This code gives error
View Answer
Answer: a
Explanation: This code maintains encapsulation. Here the private member is kept private.
Outside code can’t access the private members of class. Only objects of this class will be
able to access the public member function at maximum.

14. Encapsulation is the way to add functions in a user defined structure.


a) True
b) False
View Answer
Answer: b
Explanation: False, because we can’t call these structures if member functions are involved,
it must be called class. Also, it is not just about adding functions, it’s about binding data and
functions together.

15. Using encapsulation data security is ___________


a) Not ensured
b) Ensured to some extent
c) Purely ensured
d) Very low
View Answer
Answer: b
Explanation: The encapsulation can only ensure data security to some extent. If pointer and
addresses are misused, it may violate encapsulation. Use of global variables also makes the
program vulnerable, hence we can’t say that encapsulation gives pure security.

1. Which among the following best describes polymorphism?


a) It is the ability for a message/data to be processed in more than one form
b) It is the ability for a message/data to be processed in only 1 form
c) It is the ability for many messages/data to be processed in one way
d) It is the ability for undefined message/data to be processed in at least one way
View Answer
Answer: a
Explanation: It is actually the ability for a message / data to be processed in more than one
form. The word polymorphism indicates many-forms. So if a single entity takes more than one
form, it is known as polymorphism.

2. What do you call the languages that support classes but not polymorphism?
a) Class based language
b) Procedure Oriented language
c) Object-based language
d) If classes are supported, polymorphism will always be supported
View Answer
Answer: c
Explanation: The languages which support classes but doesn’t support polymorphism, are
known as object-based languages. Polymorphism is such an important feature, that is a
language doesn’t support this feature, it can’t be called as a OOP language.

3. Which among the following is the language which supports classes but not polymorphism?
a) SmallTalk
b) Java
c) C++
d) Ada
View Answer
Answer: d
Explanation: Ada is the language which supports the concept of classes but doesn’t support
the polymorphism feature. It is an object-based programming language. Note that it’s not an
OOP language.

4. If same message is passed to objects of several different classes and all of those can
respond in a different way, what is this feature called?
a) Inheritance
b) Overloading
c) Polymorphism
d) Overriding
View Answer
Answer: c
Explanation: The feature defined in question defines polymorphism features. Here the
different objects are capable of responding to the same message in different ways, hence
polymorphism.

5. Which class/set of classes can illustrate polymorphism in the following code?

advertisement

abstract class student


{
public : int marks;
calc_grade();
}
class topper:public student
{
public : calc_grade()
{
return 10;
}
};
class average:public student
{
public : calc_grade()
{
return 20;
}
};
class failed{ int marks; };

a) Only class student can show polymorphism


b) Only class student and topper together can show polymorphism
c) All class student, topper and average together can show polymorphism
d) Class failed should also inherit class student for this code to work for polymorphism
View Answer
Answer: c
Explanation: Since Student class is abstract class and class topper and average are inheriting
student, class topper and average must define the function named calc_grade(); in abstract
class. Since both the definition are different in those classes, calc_grade() will work in different
way for same input from different objects. Hence it shows polymorphism.

6. Which type of function among the following shows polymorphism?


a) Inline function
b) Virtual function
c) Undefined functions
d) Class member functions
View Answer
Answer: b
Explanation: Only virtual functions among these can show polymorphism. Class member
functions can show polymorphism too but we should be sure that the same function is being
overloaded or is a function of abstract class or something like this, since we are not sure
about all these, we can’t say whether it can show polymorphism or not.

7. In case of using abstract class or function overloading, which function is supposed to be


called first?
a) Local function
b) Function with highest priority in compiler
c) Global function
d) Function with lowest priority because it might have been halted since long time, because
of low priority
View Answer
Answer: b
Explanation: Function with highest priority is called. Here, it’s not about the thread scheduling
in CPU, but it focuses on whether the function in local scope is present or not, or if scope
resolution is used in some way, or if the function matches the argument signature. So all
these things define which function has the highest priority to be called in runtime. Local
function could be one of the answer but we can’t say if someone have used pointer to another
function or same function name.
8. Which among the following can’t be used for polymorphism?
a) Static member functions
b) Member functions overloading
c) Predefined operator overloading
d) Constructor overloading
View Answer
Answer: a
Explanation: Static member functions are not property of any object. Hence it can’t be
considered for overloading/overriding. For polymorphism, function must be property of object,
not only of class.

9. What is output of the following program?

class student
{
public : int marks;
void disp()
{
cout<<”its base class”
};
class topper:public student
{
public :
void disp()
{
cout<<”Its derived class”;
}
}
void main() { student s; topper t;
s.disp();
t.disp();
}

a) Its base classIts derived class


b) Its base class Its derived class
c) Its derived classIts base class
d) Its derived class Its base class
View Answer
Answer: a
Explanation: You need to focus on how the output is going to be shown, no space will be
given after first message from base class. And then the message from derived class will be
printed. Function disp() in base class overrides the function of base class being derived.

10. Which among the following can show polymorphism?


a) Overloading ||
b) Overloading +=
c) Overloading <<
d) Overloading &&
View Answer
Answer: c
Explanation: Only insertion operator can be overloaded among all the given options. And the
polymorphism can be illustrated here only if any of these is applicable of being overloaded.
Overloading is type of polymorphism.

11. Find the output of the following program.

class education
{
char name[10];
public : disp()
{
cout<<”Its education system”;
}
class school:public education
{
public: void dsip()
{
cout<<”Its school education system”;
}
};
void main()
{
school s;
s.disp();
}
}

a) Its school education system


b) Its education system
c) Its school education systemIts education system
d) Its education systemIts school education system
View Answer
Answer: a
Explanation: Notice that the function name in derived class is different from the function name
in base class. Hence when we call the disp() function, base class function is executed. No
polymorphism is used here.

12. Polymorphism is possible in C language.


a) True
b) False
View Answer
Answer: a
Explanation: It is possible to implement polymorphism in C language, even though it doesn’t
support class. We can use structures and then declare pointers which in turn points to some
function. In this way we simulate the functions like member functions but not exactly member
function. Now we can overload these functions, hence implementing polymorphism in C
language.

13. Which problem may arise if we use abstract class functions for polymorphism?
a) All classes are converted as abstract class
b) Derived class must be of abstract type
c) All the derived classes must implement the undefined functions
d) Derived classes can’t redefine the function
View Answer
Answer: c
Explanation: The undefined functions must be defined is a problem, because one may need
to implement few undefined functions from abstract class, but he will have to define each of
the functions declared in abstract class. Being useless task, it is a problem sometimes.

14. Which among the following is not true for polymorphism?


a) It is feature of OOP
b) Ease in readability of program
c) Helps in redefining the same functionality
d) Increases overhead of function definition always
View Answer
Answer: d
Explanation: It never increases function definition overhead, one way or another if you don’t
use polymorphism, you will use the definition in some other way, so it actually helps to write
efficient codes.

15. If 2 classes derive one base class and redefine a function of base class, also overload
some operators inside class body. Among these two things of function and operator
overloading, where is polymorphism used?
a) Function overloading only
b) Operator overloading only
c) Both of these are using polymorphism
d) Either function overloading or operator overloading because polymorphism can be applied
only once in a program
View Answer
Answer: d
Explanation: Both of them are using polymorphism. It is not necessary that polymorphism can
be used only once in a program, it can be used anywhere, any number of times in a single
program.

1. Which of the following is not type of class?


a) Abstract Class
b) Final Class
c) Start Class
d) String Class
View Answer
Answer: c
Explanation: Only 9 types of classes are provided in general, namely, abstract, final, mutable,
wrapper, anonymous, input-output, string, system, network. We may further divide the
classes into parent class and subclass if inheritance is used.

2. Class is pass by _______


a) Value
b) Reference
c) Value or Reference, depending on program
d) Copy
View Answer
Answer: b
Explanation: Classes are pass by reference, and the structures are pass by copy. It doesn’t
depend on the program.

3. What is default access specifier for data members or member functions declared within a
class without any specifier, in C++?
a) Private
b) Protected
c) Public
d) Depends on compiler
View Answer
Answer: a
Explanation: The data members and member functions are Private by default in C++ classes,
if none of the access specifier is used. It is actually made to increase the privacy of data.

4. Which is most appropriate comment on following class definition?

class Student
{
int a;
public : float a;
};

a) Error : same variable name can’t be used twice


b) Error : Public must come first
c) Error : data types are different for same variable
d) It is correct
View Answer
Answer: a
Explanation: Same variable can’t be defined twice in same scope. Even if the data types are
different, variable name must be different. There is no rule like Public member should come
first or last.
advertisement

5. Which is known as a generic class?


a) Abstract class
b) Final class
c) Template class
d) Efficient Code
View Answer
Answer: c
Explanation: Template classes are known to be generic classes because those can be used
for any data type value and the same class can be used for all the variables of different data
types.

6. Size of a class is _____________


a) Sum of the size of all the variables declared inside the class
b) Sum of the size of all the variables along with inherited variables in the class
c) Size of the largest size of variable
d) Classes doesn’t have any size
View Answer
Answer: d
Explanation: Classes doesn’t have any size, actually the size of object of the class can be
defined. That is done only when an object is created and its constructor is called.

7. Which class can have member functions without their implementation?


a) Default class
b) String class
c) Template class
d) Abstract class
View Answer
Answer: d
Explanation: Abstract classes can have member functions with no implementation, where the
inheriting subclasses must implement those functions.

8. Which of the following describes a friend class?


a) Friend class can access all the private members of the class, of which it is a friend
b) Friend class can only access protected members of the class, of which it is a friend
c) Friend class don’t have any implementation
d) Friend class can’t access any data member of another class but can use it’s methods
View Answer
Answer: a
Explanation: A friend class can access all the private members of another class, of which it
is a friend. It is a special class provided to use when you need to reuse the data of a class
but don’t want that class to have those special functions.

9. What is the scope of a class nested inside another class?


a) Protected scope
b) Private scope
c) Global scope
d) Depends on access specifier and inheritance used
View Answer
Answer: d
Explanation: It depends on the access specifier and the type of inheritance used with the
class, because if the class is inherited then the nested class can be used by subclass too,
provided it’s not of private type.

10. Class with main() function can be inherited.


a) True
b) False
View Answer
Answer: a
Explanation: The class containing main function can be inherited and hence the program can
be executed using the derived class names also in java.

11. Which among the following is false, for a member function of a class?
a) All member functions must be defined
b) Member functions can be defined inside or outside the class body
c) Member functions need not be declared inside the class definition
d) Member functions can be made friend to another class using the friend keyword
View Answer
Answer: c
Explanation: Member functions must be declared inside class body, though the definition can
be given outside the class body. There is no way to declare the member functions outside
the class.

12. Which syntax for class definition is wrong?


a) class student{ };
b) student class{ };
c) class student{ public: student(int a){ } };
d) class student{ student(int a){} };
View Answer
Answer: b
Explanation: Keyword class should come first. Class name should come after keyword class.
Parameterized constructor definition depends on programmer so it can be left empty also.

13. Which of the following pairs are similar?


a) Class and object
b) Class and structure
c) Structure and object
d) Structure and functions
View Answer
Answer: b
Explanation: Class and structure are similar to each other. Only major difference is that a
structure doesn’t have member functions whereas the class can have both data members
and member functions.

14. Which among the following is false for class features?


a) Classes may/may not have both data members and member functions
b) Class definition must be ended with a colon
c) Class can have only member functions with no data members
d) Class is similar to union and structures
View Answer
Answer: b
Explanation: Class definition must end with a semicolon, not colon. Class can have only
member functions in its body with no data members.

15. Instance of which type of class can’t be created?


a) Anonymous class
b) Nested class
c) Parent class
d) Abstract class
View Answer
Answer: d
Explanation: Instance of abstract class can’t be created as it will not have any constructor of
its own, hence while creating an instance of class, it can’t initialize the object members.
Actually the class inheriting the abstract class can have its instance because it will have
implementation of all members.

1) Which protocol is used for requesting a web page in


ASP.NET from the Web Server?
1. HTTP
2. TCP
3. SMTP
4. None of the above.

2) What are the types of cookies?


1. Session cookies
2. Persistent cookies
3. Dummy cookies
4. Options A and B are correct

3) What is the fully qualified name of the base class of all


server controls?
1. System.Web.UI.Control
2. System.Web.UI
3. System.Control
4. All of the above

4) Which file you should write for the connection string so


that you can access it in all the web pages for the same
application?
1. In App_Data folder
2. In Web.config file
3. In MasterPage file
4. None of the above

5) What are the advantages of AJAX?


1. AJAX is a platform-independent technology
2. It provides partial-page updates
3. Improved performance
4. All of the above
6) You need to allow users to choose their own themes. In
which page event will you write the user-selected theme?
1. Page_Load
2. Page_Render
3. Page_PreInit
4. Page_PreRender

7) Which is the first event of the ASP.NET page, when the


user requests a web page?
1. PreLoad
2. Load
3. PreInit
4. Init

8) What is the name of the Page object’s property that


determines if a Web page is being requested without data
being submitted to the server?
1. IsCallback
2. IsReusable
3. IsValid
4. IsPostBack

9) How will you specify the Cache Location?


1. You can use browser settings to specify where a page is cached.
2. You can use the Location attribute of the <%@ OutputCache %> directive to
specify where a page is cached.
3. You can use the Location attribute in QueryString to specify where a page is cached.
4. None of the above.

10) How many types of authentication ASP.NET supports?


1. Windows Authentication.
2. .NET Passport Authentication.
3. Forms Authentication.
4. All of the above.
5. 1. Which definition best describes an object?
a) Instance of a class
b) Instance of itself
c) Child of a class
d) Overview of a class
View Answer
6. Answer: a
Explanation: An object is instance of its class. It can be declared in the same way that
a variable is declared, only thing is you have to use class name as the data type.
7. 2. How many objects can be declared of a specific class in a single program?
a) 32768
b) 127
c) 1
d) As many as you want
View Answer
8. Answer: d
Explanation: You can create as many objects of a specific class as you want, provided
enough memory is available.
9. 3. Which among the following is false?
a) Object must be created before using members of a class
b) Memory for an object is allocated only after its constructor is called
c) Objects can’t be passed by reference
d) Objects size depends on its class data members
View Answer
10. Answer: c
Explanation: Objects can be passed by reference. Objects can be passed by value
also. If the object of a class is not created, we can’t use members of that class.
11. 4. Which of the following is incorrect?
a) class student{ }s;
b) class student{ }; student s;
c) class student{ }s[];
d) class student{ }; student s[5];
View Answer
12. Answer: c
Explanation: The array must be specified with a size. You can’t declare object array,
or any other linear array without specifying its size. It’s a mandatory field.
13. 5. The object can’t be __________
a) Passed by reference
b) Passed by value
c) Passed by copy
d) Passed as function
View Answer
14. Answer: d
Explanation: Object can’t be passed as function as it is an instance of some class, it’s
not a function. Object can be passed by reference, value or copy. There is no term
defined as pass as function for objects.
15. advertisement
16. 6. What is size of the object of following class (64 bit system)?
17. class student { int rollno; char name[20]; static int studentno;
};
18. a) 20
b) 22
c) 24
d) 28
View Answer
19. Answer: c
Explanation: The size of any object of student class will be of size 4+20=24, because
static members are not really considered as property of a single object. So static
variables size will not be added.
20. 7. Functions can’t return objects.
a) True
b) False
View Answer
21. Answer: b
Explanation: Functions can always return an object if the return type is same as that
of object being returned. Care has to be taken while writing the prototype of the
function.
22. 8. How members of an object are accessed?
a) Using dot operator/period symbol
b) Using scope resolution operator
c) Using member names directly
d) Using pointer only
View Answer
23. Answer: a
Explanation: Using dot operator after the name of object we can access its members.
It is not necessary to use the pointers. We can’t use the names directly because it may
be used outside the class.
24. 9. If a local class is defined in a function, which of the following is true for an object of
that class?
a) Object is accessible outside the function
b) Object can be declared inside any other function
c) Object can be used to call other class members
d) Object can be used/accessed/declared locally in that function
View Answer
25. Answer: d
Explanation: For an object which belongs to a local class, it is mandatory to declare
and use the object within the function because the class is accessible locally within
the class only.
26. 10. Which among the following is wrong?
a) class student{ }; student s;
b) abstract class student{ }; student s;
c) abstract class student{ }s[50000000];
d) abstract class student{ }; class toppers: public student{ }; topper t;
View Answer
27. Answer: b
Explanation: We can never create instance of an abstract class. Abstract classes
doesn’t have constructors and hence when an instance is created there is no facility
to initialize its members. Option d is correct because topper class is inheriting the base
abstract class student, and hence topper class object can be created easily.
28. 11. Object declared in main() function _____________
a) Can be used by any other function
b) Can be used by main() function of any other program
c) Can’t be used by any other function
d) Can be accessed using scope resolution operator
View Answer
29. Answer: c
Explanation: The object declared in main() have local scope inside main() function
only. It can’t be used outside main() function. Scope resolution operator is used to
access globally declared variables/objects.
30. 12. When an object is returned___________
a) A temporary object is created to return the value
b) The same object used in function is used to return the value
c) The Object can be returned without creation of temporary object
d) Object are returned implicitly, we can’t say how it happens inside program
View Answer
31. Answer: a
Explanation: A temporary object is created to return the value. It is created because
the object used in function is destroyed as soon as the function is returned. The
temporary variable returns the value and then gets destroyed.
32. 13. Which among the following is correct?
a) class student{ }s1,s2; s1.student()=s2.student();
b) class student{ }s1; class topper{ }t1; s1=t1;
c) class student{ }s1,s2; s1=s2;
d) class student{ }s1; class topper{ }t1; s1.student()=s2.topper();
View Answer
33. Answer: c
Explanation: Only if the objects are of same class then their data can be copied from
to another using assignment operator. This actually comes under operator
overloading. Class constructors can’t be assigned any explicit value as in option class
student{ }s1; class topper{ }t1; s1=t1; and class student{ }s1; class topper{ }t1;
s1.student()=s2.topper();.
34. 14. Which among following is correct for initializing the class below?
35. class student{
36. int marks;
37. int cgpa;
38. public: student(int i, int j){
39. marks=I;
40. cgpa=j
41. }
42. };
43. a) student s[3]={ s(394, 9); s(394, 9); s(394,9); };
b) student s[2]={ s(394,9), s(222,5) };
c) student s[2]={ s1(392,9), s2(222,5) };
d) student s[2]={ s[392,9], s2[222,5] };
View Answer
44. Answer: b
Explanation: It is the way we can initialize the data members for an object array using
parameterized constructor. We can do this to pass our own intended values to initialize
the object array data.
45. 15. Object can’t be used with pointers because they belong to user defined class, and
compiler can’t decide the type of data may be used inside the class.
a) True
b) False
View Answer
46. Answer: b
Explanation: The explanation given is wrong because object can always be used with
pointers like with any other variables. Compiler doesn’t have to know the structure of
the class to use a pointer because the pointers only points to a memory address/stores
that address.

1. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. int i, j;
4. for (i = 1; i <= 3; i++)
5. {
6. j = 1;
7. while (i % j == 2)
8. {
9. j++;
10. }
11. Console.WriteLine(i + " " + j);
12. }
13. Console.ReadLine();
14. }

a) 11 21 31
b) 1 12 13 1
c) 11 21 31
d) 1 1 2 1 3 1
View Answer
Answer: c
Explanation: Since, condition never satisfied for any value of i and j for which (i % j == 2).
Hence, j is always constant ‘1’ and ‘i’ increments for i = 1, 2, 3.
Output:
11 21 31.

2. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. float s = 0.1f;
4. while (s <= 0.5f)
5. {
6. ++s;
7. Console.WriteLine(s);
8. }
9. Console.ReadLine();
10. }

a) 0.1
b) 1.1
c) 0.1 0.2 0.3 0.4 0.5
d) No output
View Answer
Answer: b
Explanation: For the first while condition check when s = 0. If it is true as control goes inside
loop ++s increments value of s by 1 as 1+0.1 = 1.1. So, for next condition while loop fails and
hence, prints final value of s as 1.1.
Output:
1.1

3. What will be the output of the following C# code?

advertisement
1. static void Main(string[] args)
2. {
3. int i;
4. i = 0;
5. while (i++ < 5)
6. {
7. Console.WriteLine(i);
8. }
9. Console.WriteLine("\n");
10. i = 0;
11. while ( ++i < 5)
12. {
13. Console.WriteLine(i);
14. }
15. Console.ReadLine();
16. }

a)

1234

12345

b)

123

1234

c)
12345

1234

d)

12345

12345

View Answer
Answer: c
Explanation: For while(i++ < 5) current value of ‘i’ is checked first and hence prints
incremented value afterwards. So, i =1, 2, 3, 4, 5. But, for while(++i < 5) current value is
incremented first and then checks that value with given condition and hence then prints that
value. So, i = 1, 2, 3, 4.
Output:
1 2 3 4 5
1 2 3 4

4. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. int x = 0;
4. while (x < 20)
5. {
6. while (x < 10)
7. {
8. if (x % 2 == 0)
9. {
10. Console.WriteLine(x);
11. }
12. x++;
13. }
14. }
15. Console.ReadLine();
16. }

a)

1 2 3 4 5 6 7 8 9 10

11 12 13 14 15 16 17 18 19 20
b) 0 2 4 6 8 10 12 14 16 18 20
c) 0 2 4 6 8
d) 0 2 4 6 8 10
View Answer
Answer: c
Explanation: Inner while loop condition checks for even number between 0 an 10 and hence
prints number between the given range.
Output:
0 2 4 6 8

5. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. int x;
4. x = Convert.ToInt32(Console.ReadLine());
5. int c = 1;
6. while (c <= x)
7. {
8. if (c % 2 == 0)
9. {
10. Console.WriteLine("Execute While " + c + "\t" +
"time");
11. }
12. c++;
13. }
14. Console.ReadLine();
15. }
16. for x = 8.

a)

Execute while 1 time

Execute while 3 time

Execute while 5 time

Execute while 7 time

b)

Execute while 2 time

Execute while 4 time

Execute while 6 time


Execute while 8 time

c)

Execute while 1 time

Execute while 2 time

Execute while 3 time

Execute while 4 time

Execute while 5 time

Execute while 6 time

Execute while 7 time

d)

Execute while 2 time

Execute while 3 time

Execute while 4 time

Execute while 5 time

View Answer
Answer: b
Explanation: Checks condition if number is divisible by 2 then it will print it even number times
as given for x = 8 so, prints between 2 to 8 times Similarly, for x = 5, Execute 2 and 4 time.
OUTPUT:
Execute while 2 time.
Execute while 4 time.
Execute while 6 time.
Execute while 8 time.

6. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. int n, r;
4. n = Convert.ToInt32(Console.ReadLine());
5. while (n > 0)
6. {
7. r = n % 10;
8. n = n / 10;
9. Console.WriteLine(+r);
10. }
11. Console.ReadLine();
12. }
13. for n = 5432.

a) 3245
b) 2354
c) 2345
d) 5423
View Answer
Answer: c
Explanation: Reverse of number using while loop.
Output:
2345.

7. Correct syntax for while statement is:


a)

1. while
2. {
3.
4.
5.
6. }(condition);

b)

1. while(condition)
2. {
3.
4.
5. };

c)

1. while(condition)
2. {
3.
4.
5. }

d)

1. while(condition);
2. {
3.
4.
5. }
View Answer
Answer: c
Explanation: By definition.

8. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. float i = 1.0f, j = 0.05f;
4. while (i < 2.0f && j <= 2.0f)
5. {
6. Console.WriteLine(i++ - ++j);
7. }
8. Console.ReadLine();
9. }

a) 0.05f
b) 1.50f
c) -0.04999995f
d) 1.50f
View Answer
Answer: c
Explanation: for while(i = 1.0f and j = 0.05f). We, had ‘&&’ condition which gives ‘1’. So, control
enters while loop. Since, i = 1 and i++ = first execute then increment. So, first with ‘i’ value as
1.0f and ++j = first increment and then executes we had j = 1.05f and Since operation (i++ –
++j) gives us a negative sign number. So, we can stick our choice to option ‘-0.04999995f’
clearly. Now, as i = 2.0f so loop breaks.
Output:
-0.04999995f

9. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. int i = 0;
4. while (i <= 50)
5. {
6. if (i % 10 == 0)
7. continue;
8. else
9. break;
10. i += 10;
11. Console.WriteLine(i % 10);
12. }
13. }

a) code prints output as 0 0 0 0 0


b) code prints output as 10 20 30 40 50
c) infinite loop but doesn’t print anything
d) Code generate error
View Answer
Answer: c
Explanation: None.

10. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. int i = 1, j = 1;
4. while (++i <= 10)
5. {
6. j++;
7. }
8. Console.WriteLine(i+ " " +j);
9. Console.ReadLine();
10. }

a) 12 11
b) 10 11
c) 11 10
d) 11 12
View Answer
Answer: c
Explanation: As ++i, first increments then execute so, for ++i i is 11 and j++ is first execute
then increments. So, j = 10.
Output:
11 10.

11. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. int i = 1;
4. while (i <= 1)
5. {
6. if ('A' < 'a')
7. {
8. Console.WriteLine("Hello...");
9. }
10. else
11. {
12. Console.WriteLine("Hi...");
13. }
14. i++;
15. }
16. Console.ReadLine();
17. }

a) Hi…
b) Hello….
c) Hi…infinite times
d) Hello infinite times
View Answer
Answer: b
Explanation: Ascii value of ‘A’ is 65 and ‘a’ is 97. So, clearly ‘A’ < ‘a’.
Output:
Hello.

12. What will be the output of the following C# code?

1. static void Main(string[] args)


2. {
3. int i = 0;
4. while (i++ != 0) ;
5. Console.WriteLine(i);
6. Console.ReadLine();
7. }

a) -127 to +127
b) 0 to 127
c) 1
d) Infinite loop condition
View Answer
Answer: c
Explanation: i++ = first executes then increments as i = 0. So, i++ != 0, which is false clearly
as i = 0. Now, control goes inside loop with i = 1. So, statement prints i = 1.
Output:

A SaveFileDialog control is used to save a file using Windows SaveFileDialog. A typical


SaveFileDialog looks like Figure 1 where you can see the Windows Explorer type
features to navigate through folders and save a file in a folder.
Figure 1

Creating a SaveFileDialog

We can create a SaveFileDialog control using a Forms designer at design-time or using


the SaveFileDialog class in code at run-time (also known as dynamically). Unlike other
Windows Forms controls, a SaveFileDialog does not have and not need visual
properties like others.

Note
Even though you can create a SaveFileDialog at design-time it is easier to create a
SaveFileDialog at run-time.

Design-time

To create a SaveFileDialog control at design-time, you simply drag and drop a


SaveFileDialog control from Toolbox to a Form in Visual Studio. After you drag and drop
a SaveFileDialog on a Form, the SaveFileDialog looks like Figure 2.

Figure 2
Adding a SaveFileDialog to a Form adds the following two lines of code.

1. private System.Windows.Forms.SaveFileDialog saveFileDialog1;


2. this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();

Run-time

Creating a SaveFileDialog control at run-time is merely a work of creating an instance of


SaveFileDialog class, setting its properties and adding SaveFileDialog class to the Form
controls.

The first step to create a dynamic SaveFileDialog is to create an instance of


SaveFileDialog class. The following code snippet creates a SaveFileDialog control
object.

1. SaveFileDialog SaveFileDialog1 = new SaveFileDialog();

ShowDialog method displays the SaveFileDialog.

1. SaveFileDialog1.ShowDialog();

Once the ShowDialog method is called, you can browse and select a file.

Setting SaveFileDialog Properties

After you place a SaveFileDialog control on a Form, the next step is to set properties.

The easiest way to set properties is from the Properties Window. You can open
Properties window by pressing F4 or right clicking on a control and selecting Properties
menu item. The Properties window looks like Figure 3.
Figure 3

Initial and Restore Directories

InitialDirectory property represents the directory to be displayed when the open file
dialog appears the first time.

1. SaveFileDialog1.InitialDirectory = @"C:\";

If RestoreDirectory property is set to true that means the open file dialog box restores
the current directory before closing.

1. SaveFileDialog1.RestoreDirectory = true;

Title

Title property is used to set or get the title of the open file dialog.

1. SaveFileDialog1.Title = "Browse Text Files";

Default Extension

DefaultExtn property represents the default file name extension.

1. SaveFileDialog1.DefaultExt = "txt";
Filter and Filter Index

Filter property represents the filter on an open file dialog that is used to filter the type of
files to be loaded during the browse option in an open file dialog. For example, if you
need users to restrict to image files only, we can set Filter property to load image files
only.

1. SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)


|*.*";

FilterIndex property represents the index of the filter currently selected in the file dialog
box.

1. SaveFileDialog1.FilterIndex = 2;

Check File Exists and Check Path Exists

CheckFileExists property indicates whether the dialog box displays a warning if the user
specifies a file name that does not exist. CheckPathExists property indicates whether
the dialog box displays a warning if the user specifies a path that does not exist.

1. SaveFileDialog1.CheckFileExists = true;
2. SaveFileDialog1.CheckPathExists = true;

File Name and File Names

FileName property represents the file name selected in the open file dialog.

1. textBox1.Text = SaveFileDialog1.FileName;

If MultiSelect property is set to true that means the open file dialog box allows multiple
file selection. The FileNames property represents all the files selected in the selection.

1. this.SaveFileDialog1.Multiselect = true;
2. foreach(String file in SaveFileDialog1.FileNames) {
3. MessageBox.Show(file);
4. }

Sample Example

The following code snippet is the code for Save button click event handler. Once a text
file is selected, the name of the text file is displayed in the TextBox.

1. private void SaveButton_Click(object sender, EventArgs e) {


2. SaveFileDialog saveFileDialog1 = new SaveFileDialog();
3. saveFileDialog1.InitialDirectory = @ "C:\";
4. saveFileDialog1.Title = "Save text Files";
5. saveFileDialog1.CheckFileExists = true;
6. saveFileDialog1.CheckPathExists = true;
7. saveFileDialog1.DefaultExt = "txt";
8. saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files
(*.*)|*.*";
9. saveFileDialog1.FilterIndex = 2;
10. saveFileDialog1.RestoreDirectory = true;
11. if (saveFileDialog1.ShowDialog() == DialogResult.OK) {

12. textBox1.Text = saveFileDialog1.FileName;


13. }
14. }

Summary

A SaveFileDialog control allows users to launch Windows Save File Dialog and let them
save files. In this article, we discussed how to use a Windows Save File Dialog and set
its properties in a Windows Forms application.

Introduction

This article about saving a text file C# example using a System.IO.File. These examples show
various ways to write text to a file. The first two examples use static convenience methods on
the System.IO.File class to write each element of any IEnumerable<string> and a string to a text
file. This example shows you how to add a text to a file when you have to process each line
individually as you write to the file. Examples overwrite all existing content in the file, but this
example shows you how to append text to an existing file.

These examples all write string literals to files, but more likely you will want to use
the Format method, which has many controls for writing different types of values right or left-
justified in a field, with or without padding, and so on.

Let’s make a program to write a text file C# windows form. We'll follow the steps to make it:

Step 1

Create a new application project. In Visual Studio, on the menu click File> New > Project. For
more details, see the following menu on the display.
Step 2

Then the New Project window will appear


Step 3

Write down the name of the project that will be created on a field Name. Specify the directory
storage project by accessing the field Location. Next, give the name of the solution in the
Solution Name. Then click OK.
Step 4

Create a new windows form like below:

Step 5
Next, go back to the Windows form and view the code to write the following program listing:

1. using System;
2. using System.Collections.Generic;
3. using System.ComponentModel;
4. using System.Data;
5. using System.Drawing;
6. using System.Linq;
7. using System.Text;
8. using System.Windows.Forms;
9. using System.IO;namespace Save_File_txt
10. {
11. public partial class Form1 : Form
12. {
13. public static string dirParameter = AppDomain.Curren
tDomain.BaseDirectory + @"\file.txt";
14. public Form1()
15. {
16. InitializeComponent();
17. } private void button1_Click(object sender, E
ventArgs e)
18. {
19. SaveEvent();
20. } public void SaveEvent()
21. {
22. DialogResult result;
23. result = MessageBox.Show("Do you want to save fi
le?", "Konfirmasi", MessageBoxButtons.YesNo, MessageBoxIcon.Quest
ion); if (result == DialogResult.No)
24. {
25. return;
26. }
27. if (result == DialogResult.Yes)
28. {
29. try
30. {
31. if (textBox1.Text != null && textBox2.Te
xt != null && textBox3.Text != null)
32. {
33. saveFile(textBox1.Text, textBox2.Tex
t, textBox3.Text);
34. }
35. }
36. catch (Exception err)
37. {
38. MessageBox.Show(err.ToString());
39. }
40. }
41. } public void saveFile(string name,string tel
ephone, string address)
42. {
43. string Msg = name + ";" + telephone + ";" + addr
ess;
44.
45. // Save File to .txt
46. FileStream fParameter = new FileStream(dirParameter,
FileMode.Create, FileAccess.Write);
47. StreamWriter m_WriterParameter = new StreamWrite
r(fParameter);
48. m_WriterParameter.BaseStream.Seek(0, SeekOrigin.End);

49. m_WriterParameter.Write(Msg);
50. m_WriterParameter.Flush();
51. m_WriterParameter.Close();
52. }
53. }
54. }

Step 6

After you write down the program listings, press the F5 key to run the program and if you
successfully, the result is:
Step 7

Fill the textbox then click button “Save File”, so the result will save the file to your directory
application path like shown below:

We have explained how to make a simple program to save a text file dialog in C# using Visual
Studio 2010 and MySQL. For those of you who want to download the source code of the
program, you also can. Hopefully, this discussion was helpful to you.

WHAT IS FILESTREAM CLASS IN C#?


FileStream Class is used to perform the basic operation of reading and writing operating
system files. FileStream class helps in reading from, writing and closing files.

HOW TO USE FILESTREAM CLASS IN C#?


In order to use FileStream class you need to include System.IO namespace and then create
FileStream Object to create a new file or open an existing file.

1. FileStream <object_name> = new FileStream( <file_name>, <FileMode Enumerator>, <FileAcc


ess Enumerator>, <FileShare Enumerator>);

FileMode – It specifies how to operation system should open the file. It has following
members

1. Append - Open the file if exist or create a new file. If file exists then place cursor at
the end of the file.
2. Create - It specifies operating system to create a new file. If file already exists then
previous file will be overwritten.
3. CreateNew - It create a new file and If file already exists then throw IOException.
4. Open – Open existing file.
5. Open or Create – Open existing file and if file not found then create new file.
6. Truncate – Open an existing file and cut all the stored data. So the file size becomes
0.

FileAccess – It gives permission to file whether it will


open Read, ReadWrite or Write mode. FileShare – It opens file with following share
permission.

1. Delete – Allows subsequent deleting of a file.


2. Inheritable – It passes inheritance to child process.
3. None – It declines sharing of the current files.
4. Read- It allows subsequent opening of the file for reading.
5. ReadWrite – It allows subsequent opening of the file for reading or writing.
6. Write – Allows subsequent opening of the file for writing.

PROGRAMMING EXAMPLE
In this programming Example we will create a new file "CsharpFile.txt" and saves it on
disk. And then we will open this file, saves some text in it and then close this file.

CREATE A BLANK .TXT FILE USING FILESTREAM

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace FileStream_CreateFile
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. FileStream fs = new FileStream("D:\\csharpfile.txt", FileMode.Create);
15. fs.Close();
16. Console.Write("File has been created and the Path is D:\\csharpfile.txt
");
17. Console.ReadKey();
18. }
19. }
20. }

Output
File has been created and the Path is D:\\csharpfile.txt

Explanation:
In the above program I added System.IO namespace so that I could use FileStream class in
my program. Then I created an object of FileStream class fs to create a
new csharpfile.txt in D drive.

OPEN CSHARPFILE.TXT AND WRITE SOME TEXT IN IT

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace AccessFile
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. FileStream fs = new FileStream("D:\\csharpfile.txt", FileMode.Append);
15. byte[] bdata=Encoding.Default.GetBytes("Hello File Handling!");
16. fs.Write(bdata, 0, bdata.Length);
17. fs.Close();
18. Console.WriteLine("Successfully saved file with data : Hello File Handling!
");
19. Console.ReadKey();
20. }
21. }
22. }

Output
Successfully saved file with data : Hello File Handling!

_
Explanation
In the above program again I created object as fs of FileStrem class. Then Encoded a string
into bytes and kept into byte[] variable bdata and finally using Write() method of
FileStream stored string into file.

READ DATA FROM CSHARPFILE.TXT FILE

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using System.IO;
7.
8. namespace FileStream_ReadFile
9. {
10. class Program
11. {
12. static void Main(string[] args)
13. {
14. string data;
15. FileStream fsSource = new FileStream("D:\\csharpfile.txt", FileMode.Open, F
ileAccess.Read);
16. using (StreamReader sr = new StreamReader(fsSource))
17. {
18. data = sr.ReadToEnd();
19. }
20. Console.WriteLine(data);
21. Console.ReadLine();
22. }
23. }
24. }

Output
Hello File Handling!

Explanation
In the above example I opened file in a Read permission and use StreamReader class to read
file.

SUMMARY
In this chapter you have learned FileStream Class with detailed and complete described
programming example. In the next chapter you will learn about StreamWriter Class.
C# TextBox Control
A TextBox control is used to display, or accept as input, a single line of
text. This control has additional functionality that is not found in the
standard Windows text box control, including multiline editing and
password character masking.

A text box object is used to display text on a form or to get user input
while a C# program is running. In a text box, a user can type data or paste
it into the control from the clipboard.

For displaying a text in a TextBox control , you can code like this.

You can also collect the input value from a TextBox control to a variable
like this way.
C# TextBox Properties

You can set TextBox properties through Property window or through


program. You can open Properties window by pressing F4 or right click
on a control and select Properties menu item.

The below code set a textbox width as 250 and height as 50 through source
code.

Background Color and Foreground Color

You can set background color and foreground color through property
window and programmatically.
Textbox BorderStyle

You can set 3 different types of border style for textbox, they are None,
FixedSingle and fixed3d.

TextBox Events

Keydown event

You can capture which key is pressed by the user using KeyDown event

e.g.

TextChanged Event

When user input or setting the Text property to a new value raises the
TextChanged event
e.g.

Textbox Maximum Length

Sets the maximum number of characters or words the user can input into
the text box control.

Textbox ReadOnly

When a program wants to prevent a user from changing the text that
appears in a text box, the program can set the controls Read-only property
is to True.

Multiline TextBox

You can use the Multiline and ScrollBars properties to enable multiple
lines of text to be displayed or entered.
Textbox password character

TextBox controls can also be used to accept passwords and other sensitive
information. You can use the PasswordChar property to mask characters
entered in a single line version of the control

The above code set the PasswordChar to * , so when the user enter
password then it display only * instead of typed characters.

How to Newline in a TextBox

You can add new line in a textbox using many ways.

or

How to retrieve integer values from textbox ?


Parse method Converts the string representation of a number to its integer
equivalent.

String to Float conversion

String to Double conversion

Looking for a C# job ?


There are lot of opportunities from many reputed companies in the world.
Chances are you will need to prove that you know how to work with .Net
Programming Language. These C# Interview Questions have been
designed especially to get you acquainted with the nature of questions you
may encounter during your interview for the subject of .Net
Programming. Here's a comprehensive list of .Net Interview Questions,
along with some of the best answers. These sample questions are framed
by our experts team who trains for .Net training to give you an idea of
type of questions which may be asked in interview.

Go to... C# Interview Questions

How to allow only numbers in a textbox


Many of us have faced a situation where we want the user to enter a
number in a TextBox. Click the following link that are going to make a
Numeric Textbox which will accept only numeric values; if there are any
values except numeric. More about.... How do I make a textbox that only
accepts numbers

Autocomplete TextBox

From the latest version of Visual Studio, some of the controls support
Autocomplete feature including the TextBox controls. The properties like
AutoCompleteCustomSource, AutoCompleteMode and
AutoCompleteSource to perform a TextBox that automatically completes
user input strings by comparing the prefix letters being entered to the
prefixes of all strings in a data source. More about.... C# Autocomplete
TextBox

From the following C# source code you can see some important property
settings to a TextBox control.

Next : C# ComboBox

Download Source Code

Print Source Code

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
textBox1.Width = 250;
textBox1.Height = 50;
textBox1.Multiline = true;
textBox1.BackColor = Color.Blue;
textBox1.ForeColor = Color.White;
textBox1.BorderStyle = BorderStyle.Fixed3D;
}

private void button1_Click(object sender, EventArgs e)


{
string var;
var = textBox1.Text;
MessageBox.Show(var);
}
}
}

With PascalCase, the first letter of every word in the identifier is upper case.

With camelCase, the first letter of the first word in the identifier is lower case, while
the first letter of every subsequent word is uppercase.

In camel casing, names start with a lower case but each proper word in the name is
capitalized and so are acronyms. For example, commonly used tokens in many languages
such as toString, checkValidity, lineHeight, timestampToLocalDateTime, etc. are all examples
of camel casing.

Pascal casing is similar to camel casing except that the first letter also starts with a capital
letter (SomeClass instead of someClass).

1. Camel Case (ex: someVar, someClass, somePackage.xyz).


2. Pascal Case (ex: SomeVar, SomeClass, SomePackage.xyz).
Advanced Topics in C Sharp Quiz Questions and AnswersPDFDownload eBook

Assessment

Advanced Topics in C Sharp quiz questions and answers, advanced topics in c sharp MCQs
with answers PDF 1 to practice app development mock tests for online graduate programs.
Practice "Advanced Topics in C#" quiz questions and answers, advanced topics in c sharp
Multiple Choice Questions (MCQ) to practice c sharp test with answers for online information
technology degree. Free advanced topics in c sharp MCQs, MCQs, boolean logic, type
conversion, just in time compiler and common intermediate language, function overloading,
advanced topics in c sharp test prep for programming certifications.

"In order to lock/unlock an object use the", advanced topics in c sharp Multiple Choice
Questions (MCQ) with choicesenter and exit methods, lock and unlock methods, close and
open methods, and close and allow methodsfor online computer science bachelors degree.
Learn advanced topics in c# questions and answers to improve problem solving skills for IT
certifications.

Quiz on Advanced Topics in C SharpPDFDownload eBook1

Advanced Topics in C Sharp Quiz

MCQ: In order to lock/unlock an object use the

lock and unlock methods

enter and exit methods

close and open methods

close and allow methods

AnswerD

Function Overloading Quiz

MCQ: Choose from the given options the one that can be overloaded

constructors

methods

parameters

operators

AnswerD

Just In Time compiler and Common Intermediate Language Quiz


MCQ: The original name of Common Intermediate Language is

MSIL(Microsoft Intermediate Language)

JIT(Just In Time compiler)

IL(Intermediate Language)

Both a and c

AnswerD

Type conversion Quiz

MCQ: The disadvantages of Explicit type conversion are that it

makes program memory heavier

results in loss of data

is potentially Unsafe

is memory consuming

AnswerB

Boolean Logic Quiz

MCQ: The output for following code will be <br/> <code> static void Main(string[] args)

int a = 3, b = 5, c = 1;

int z = ++b;

int y = ++c;

b = Convert.ToInt32((Convert.ToBoolean(z)) && (Convert.ToBoolean(y)) ||


Convert.ToBoolean(Convert.ToInt32(!(++a == b))));

a = Convert.ToInt32(Convert.ToBoolean(c) || Convert.ToBoolean(a--));

Console.WriteLine(++a);

Console.WriteLine(++b);

Console.WriteLine(c);

} </code>

2 ,2 ,1

2 ,0 ,9
2 ,2 ,2

2 ,3 ,2

AnswerC

Advanced Multiple Choice Questions Of C Sharp (C#).NET

By: Prof. Fazal Rehman Shamil

Last modified on May 27th, 2019

Advanced Multiple Choice Questions Of C Sharp (C#).NET

1: Menu bar contains a set of ……. to provide controls in the form...

a) Status

b) Tool

c) Menu

d) Progress

Answer - Click Here:

2: Which of the following is the same as the codewindow…

a) procedure

b) debug

c)object

d)form

Answer - Click Here:

3: Which of the following function translates a numeric value to a variable…


a) mod

b) val

c) build In

d) balance

Answer - Click Here:

4: Which of the following is true about C#…

a) can be compiled on a variety of computer platforms

b) It is a part of.Net Framework .

c) It is component oriented

d) All of the above

Answer - Click Here:

5: Choose which one is converts a type to a string…

a) toSbyte

b) tosingle

c) toString.

d) toInt64

Answer - Click Here:

6: Preprocessor allows testing a symbol to see if they evaluate to true…


a) undef

b) define

c) elif

d) if

Answer - Click Here:

7: Which of the following String method used to compare two strings…

a)concat()

b) copy()

c)Compare

d) compare to

Answer - Click Here:

8: Which of the following property represents the current position of the stream…

a)long Position

b)int Length

c) long Length

d)All of these

Answer - Click Here:

9: Which of the following statements is not correct about constructors…

a) a constructor can be a static constructor


b) a constructor cannot be overloaded

c) constructor cannot be declared as private

d) both b and c

Answer - Click Here:

10: Which of the following is not true about destructor…

a) destructors can have modifiers or parameters

b) Destructors cannot be inherited or overloaded

c) class can have one destructor only

d) all of above

Answer - Click Here:

11: Which of the following is not a characteristic of exception handling…

a) catch

b) try

c)finally

d) thrown

Answer - Click Here:

12: Which of the following option is correct for an example of “instanceof”…

a) a function

b) a boolean
c) a lnguage construct

d) an operator

Answer - Click Here:

You might also like