Mcqss
Mcqss
Mcqss
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();
}
richTextBox1.Redo();
}
richTextBox1.Copy();
}
richTextBox1.Paste();
}
richTextBox1.Cut();
}
}
}
////////////////////
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();
}
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= "";
}
else
textBox_Result.Text = textBox_Result.Text + button.Text;
}
else {
operationPerformed = button.Text;
resultValue = Double.Parse(textBox_Result.Text);
labelCurrentOperation.Text = resultValue + " " + operationPerformed;
isOperationPerformed = true;
}
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.
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.
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
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.
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
class Program
obj.name = "Akshay";
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;
Answer. c)
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
Console.WriteLine("first method");
first();
Console.WriteLine("second method");
Console.WriteLine(i);
second();
class program
{
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)
using System;
class program
int num = 2;
Console.WriteLine(num);
Console.ReadLine();
a) 8
b) 0
c) 2
d) 16
View answer.
Answer. a)
using System;
class program
fun1(ref arr);
Console.ReadLine();
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)
using System;
class program
{
int x = 4 ,b = 2;
x -= b/= x * b;
Console.ReadLine();
a) 4 2
b) 0 4
c) 4 0
d) None of the mentioned
View answer.
Answer. c)
using System;
class program
int x = 8;
int b = 16;
int c = 64;
x /= c /= b;
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)
using System;
class sample
int i;
double k;
public sample (int ii, double kk)
i = ii;
k = kk;
Console.WriteLine(j);
~sample()
double j = i - k;
Console.WriteLine(j);
class Program
a) 0 0
b) 11.5 0
c) Compile time error
d) 11.5 6.5
View answer.
Answer. d)
using System;
class sum
int num1;
int num2;
int num3;
this.num1 = a;
this.num2 = b;
this.num3 = c;
~ sum()
class Program
a) 0
b) 180
c) Compile time error
d) 18
View answer.
Answer. b)
using System;
class Program
int num = 5;
Console.ReadLine();
static void Mul (int num, ref int square, ref int cube)
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;
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:
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
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
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
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
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.
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.
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)
b)
c)
d)
View Answer
Answer: b
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)
b)
c)
class baseclass
int a = 10;
A.Console.writeline( a + ” ” + this.a);
C.console.writeline(a + ” ” + base.a);
D.console.writeline(base.a + ” ” + a);
View Answer
Workspace
Report
Discuss
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: Option B
Explanation:
enum per
a,
b,
c,
d,
per.a = 10;
Console.writeline(per.b);
A.11
B.1
C.2
View Answer
Workspace
Report
Discuss
Answer: Option D
Explanation:
It will report an error since enum element cannot be assigned a value outside the enum declaration.
B.static
C.base
D.extend
View Answer
Workspace
Report
Discuss
Answer: Option C
Explanation:
namespace ConsoleApplication4
abstract class A
{
public int i;
class B: A
public int j;
sum = i + j;
class Program
obj.i = 2;
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: 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
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?
View Answer
Ans : A
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.
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.
View Answer
Ans : D
5. ASP.NET is?
C. Both A and B
Ans : C
B. To store the global information and variable definitions for the application
View Answer
Ans : B
Explanation: Web.config file is used to store the global information and variable definitions for the
application
View Answer
Ans : B
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.
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
View Answer
Ans : C
interface calc
public int x;
x = i * i;
public int x;
x = i / i;
class Program
arr1.x = 0;
arr2.x = 0;
arr1.cal(2);
arr2.cal(2);
Console.ReadLine();
A.0 0
B.2 2
C.4 1
D.1 4
View Answer
Workspace
Report
Discuss
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
B.Interface
C.intf
D.Intf
View Answer
Workspace
Report
Discuss
Answer: Option A
Explanation:
8.Correct way to define operator method or to perform operator overloading is?A.public static
op(arglist)
{
}
View Answer
Workspace
Report
Discuss
Answer: Option C
Explanation:
class maths
public int x;
public double y;
x = a + b;
return x;
{
y = c + d;
return (int)y;
public maths()
this.x = 0;
this.y = 0;
class Program
int a = 4;
double b = 3.5;
obj.add(a, a);
obj.add(b, b);
Console.ReadLine();
A.4, 3.5
B.8, 0
C.7.5, 8
D.8, 7
View Answer
Workspace
Report
Discuss
Answer: Option D
Explanation:
class A
public int i;
Console.WriteLine(i);
class B: A
public int j;
Console.WriteLine(j);
}
class Program
obj.i = 1;
obj.j = 2;
obj.display();
Console.ReadLine();
A.0
B.2
C.1
View Answer
Workspace
Report
Discuss
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
class Program
b.f1 ();
b.f2 ();
b.f3 ();
View Answer
Workspace
Report
Discuss
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
Console.WriteLine(obj.fact(4)*obj.fact(2));
A.64
B.60
C.120
D.48
View Answer
Workspace
Report
Discuss
Answer: Option D
Explanation:
Output : 48
13.The correct way to define a variable of type struct abc among the following is?
struct abc
B.abc();
C.abc e;
e = new abc;
View Answer
Workspace
Report
Discuss
Answer: Option A
Explanation:
Ans: A
Ans: C
Ans: B
Ans : D
Ans: A
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
Ans: C
Ans: B
Ans: D
Ans: D
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
class sample
int i;
double k;
i = ii;
k = kk;
double j = (i) + (k);
Console.WriteLine(j);
~sample()
double j = i - k;
Console.WriteLine(j);
class Program
A. 0 0
B. 11.5 0
C. Compile-time error
D. 11.5 6.5
Ans : D
class program
int x = 8;
int b = 16;
int c = 64;
x /= c /= b;
Console.ReadLine();
A. 2 16 4
B. 4 8 16
C. 2 4 8
D. 8 16 64
Ans: A
Ans: C
Ans: D
Ans: B
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
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
Ans: C
1. What will be the output of the following C# code?
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 :
advertisement
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.
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.
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?
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.
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) 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.
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 .
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.
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.
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
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. 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
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
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
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
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
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. }
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. }
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. }
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
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
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)
b)
c)
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()
{
}
}
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.
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.
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.
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.
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.
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.
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.
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.
This phase has two steps executing the action and finally sending the response as a result to
the view.
There are total of nine return types we can use to return results from the controller to view.
ViewResult (View)
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.
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)
javascriptResult (javascript)
This return type is used to return JavaScript code that will run in the browser.
FileResult (File)
EmptyResult
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
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.
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.
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
1. publicclassActionFilterDemoController: Controller
2. {
3. [HttpGet]
4. OutputCache(Duration = 10)]
5. publicstringIndex()
6. {
7. returnDateTime.Now.ToString("T");
8.
9. }
10. }
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
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.
{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
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
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
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.
With MVC, you can create your own helpers, or use the built in 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
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.
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#
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".
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.
Example
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.
Why is Razor?
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 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.
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.
Answer
C# Example
Learn more here - Introduction to Microsoft ASP.NET MVC 3 Razor View Engine
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>
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();
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.
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.
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.
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.
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.
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:
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
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.
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.
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".
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
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
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.
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
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
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
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.
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.
Here are more Similarities and Dissimilarities Between MVC and Web Forms.
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.
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
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. }
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
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
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
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>
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.
Answer - Tempdata
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. @ {
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.
ViewBag.Name = "Yogesh";
Calling of ViewDatais :
ViewData["Name"] = "yogesh";
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.
1. Required
2. RegularExpression
3. Range
Specifies the Range of values between which the property values are checked.
4. StringLength
5. MaxLength
Specifies the Max length for the property value.
6. MinLength
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>
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.
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
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.
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. }
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:
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);
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!
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.
Custom Exception Filters must implement the builtinIExceptionFilter interface. The interface
looks as in the following,
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.
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.
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):
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 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.
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 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).
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
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.
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>
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.
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.
Learn more here - GET and POST Calls to Controller's Method in MVC
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.
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.
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
View Answer
Workspace
Report
Discuss
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)].
View Answer
Workspace
Report
Discuss
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
View Answer
Workspace
Report
Discuss
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: 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()
View Answer
Workspace
Report
Discuss
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
2. C# developed by?
A. IBM
B. Google
C. Microsoft
D. Facebook
View Answer
Ans : C
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: 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
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: 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: 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)
C.write()
D.None of the mentioned
View Answer
Workspace
Report
Discuss
Answer: Option B
Explanation:
Writes a subrange of count bytes from the array buffer,beginning at buffer[offset], returning the
number of bytes written.
B.0
C.False
View Answer
Workspace
Report
Discuss
Answer: Option D
Explanation:
Console.ReadLine();
A.efil evoli
B.lifelove i
C.efilevol i
D.efil evol i
View Answer
Workspace
Report
Discuss
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
(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
View AnswerAns: B
Question: 4
(A) Abstracts
(B) Attributes
(C) Properties
(D) Dimensions
View AnswerAns: B
Attributes
Question: 5
(B) Constants
(C) Objects
(D) Methods
View AnswerAns: C
Objects
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)
{
}
}
Answer: (c).class a: a1
{
int a1.fun(int i)
{
}
}
A- get
B- set
C- add
Answer : D
Explanation
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.
A- get
B- set
C- add
Answer : D
Explanation
Show Answer
A- The Object Type is the ultimate base class for all data types in C# Common Type System (CTS).
C- The object types can be assigned values of any other types, value types, reference types, predefined
or user-defined types.
Answer : D
Explanation
Hide Answer
A- ToDecimal
B- ToDouble
C- ToInt16
D- ToInt32
Answer : D
Explanation
Show Answer
B- ToUInt16
C- ToSingle
D- ToString
Answer : B
Explanation
Show Answer
Answer : C
Explanation
Hide Answer
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.
Answer : D
Explanation
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.
Answer : C
Explanation
Hide Answer
A- true
B- false
Answer : A
Explanation
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.
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
A- You can store any type of value in the dynamic data type variable.
Answer : C
Explanation
Hide Answer
A- ToDecimal
B- ToDouble
C- ToInt16
D- ToInt32
Answer : D
Explanation
Hide Answer
A- ToType
B- ToUInt16
C- ToSingle
D- ToString
Answer : B
Explanation
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
A- Structures can have methods, fields, indexers, properties, operator methods, and events.
C- You cannot define a default constructor for a structure. The default constructor is automatically
defined and cannot be changed.
Answer : D
Explanation
Hide Answer
Answer : D
Explanation
Show Answer
A- true
B- false
Answer : A
Explanation
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
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
(A) Void
(B) Inline
(C) Friend
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
(A) Inline
(B) Public
(C) Friend
View AnswerAns: A
Inline
Question: 10
:: is a ___
View AnswerAns: D
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.
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.
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)
b)
c)
d)
View Answer
Answer: b
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)
b)
c)
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
Answer: (c).System.Text
42. Select the method used to write single byte to a file?
a. Write()
b. Wrteline()
c. WriteByte()
Answer: (c).WriteByte()
43. Select the namespace on which the stream classes are defined?
a. System.IO
b. System.Input
c. System.Output
44. Choose the class on which all stream classes are defined?
a. System.IO.stream
b. Sytem.Input.stream
c. System.Output.stream
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()
c. write()
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()
c. write()
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()
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
Answer: (a).Linker
b. [assembly: AssemblyDescription(“Csharp”)].
c. [AssemblyDescription(“Csharp”)].
d. (Assembly:AssemblyDescription(“Csharp”)].
a. By name
b. By address
c. By value
d. By reference
b. (Serializable())class sample
{
a. Enum
b. Event
c. Interface
d. Namespace
Answer: (d).Namespace
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
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?
b. [assembly : Employer(“Ankit”,employeeid.one)].
8. Which of the following is the correct statement about inspecting an attribute in C#.NET?
b. Class
c. Assembly
a. compile time
b. run time
c. design time
d. linking time
Step 1 - Open Visual Studio then select "File" -> "New" -> "Project..." then seelct "Visual C#" ->
"Class library".
(I give it the name "Calculation".)
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.
Step 1 - Open Visual Studio then select "File" -> "New" -> "Project..." then select "Visual C#" ->
"Windows Forms application".
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
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
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
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
Answer: (b).3
15. Select the correct methodS provided by Console.In?
a. Read(), ReadLine()
b. ReadKey(), ReadLine()
d. ReadKey(), ReadLine()
16. Choose the output returned when read() reads the character from the console?
a. String
b. Char
c. Integer
d. Boolean
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
Answer: (c).-1
18. Choose the object of TextReader class.
a. Console.In
b. Console.Out
c. Console.Error
Answer: (a).Console.In
a. Console.In
b. Console
c. Console.Error
Answer: (c).Console.Error
int a = 10, b = 0;
int result;
try
{
Console.Error.WriteLine(exc.Message);
Console.ReadLine();
b. 0
a. Write
b. WriteLine
c. WriteKey
Console.Read();
c. Runs successfully, ask for input and hence displays the result
d. Syntax Error
Answer: (c).Runs successfully, ask for input and hence displays the result
a. InterruptedException
b. SystemException
c. SystemInputException
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()
Answer: (c).read()
25. Which of these method used to read strings from the console?
a. get()
b. getline()
c. read()
d. readLine()
Answer: (d).readLine()
26. Which among the following methods are used to write characters to a string?
a. StreamWriter
b. StreamReader
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()
Answer: (b).ReadKey()
28. What is the output returned by Console if ReadLine() stores I/O error?
a. 1
b. 0
c. False
29. What would be the output for following input from the console as a character?
static void Main(string[] args)
char s;
s = Convert.ToChar(Console.ReadLine());
Console.Read();
30. Name the method/methods used to read byte streams from the file?
a. ReadByte()
b. Read
c. Readkey()
Answer: (a).ReadByte()
Question: 1
View AnswerAns: D
User Defined Type
Question: 2
(A) ,(comma)
(B) .(dot)
View AnswerAns: C
; (semi colon)
Question: 3
View AnswerAns: A
Nesting functions
Question: 4
(A) Specifications
View AnswerAns: C
Visibility labels
Question: 5
View AnswerAns: C
Member functions
Question: 6
(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
View AnswerAns: C
Both (a) and (b)
Question: 9
View AnswerAns: B
Question: 10
(A) Private
(B) Public
(C) Protected
View AnswerAns: B
Public
Question: 1
(C) + operator
View AnswerAns: B
Dot operator
Question: 2
(A) .
(B) ;
(C) :
(D) #
View AnswerAns: B
Question: 3
(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
(A) Protected
(B) Public
(C) Object
(D) Class
View AnswerAns: D
Class
Question: 7
View AnswerAns: A
Question: 8
(A) C
(B) C++
(C) Basic
(D) None
View AnswerAns: B
C++
Question: 9
View AnswerAns: A
Question: 10
(A) Logo
(B) COBOL
(C) BASIC
(D) PROLOG
View AnswerAns: A
Logo
Question: 1
(B) Advanced C
(C) Deep C
(D) D
View AnswerAns: A
C with classes
Question: 2
(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
View AnswerAns: D
Member functions can be of static type
Question: 3
View AnswerAns: A
Question: 4
View AnswerAns: A
Braces i.e.., {}
Question: 5
(A) Encapsulation()
(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
View AnswerAns: D
Data members
Question: 7
Declaration and function definitions are two specifications of which of the following
(A) Comments
(B) Class
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
View AnswerAns: C
Public
Question: 9
Question: 10
View AnswerAns: C
Question: 11
(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
View AnswerAns: D
within class
Question: 14
(A) only by member functions of its own class and friend functions
View AnswerAns: A
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
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.
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;
}
class hero
{
char name[10];
public : void disp()
{
cout<<name;
}
};
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.
advertisement
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();
}
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();
}
}
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.
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.
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.
class Student
{
int a;
public : float a;
};
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.
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.
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
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
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
a)
b)
c)
d)
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.
a) 3245
b) 2354
c) 2345
d) 5423
View Answer
Answer: c
Explanation: Reverse of number using while loop.
Output:
2345.
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.
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
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.
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.
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:
Creating a SaveFileDialog
Note
Even though you can create a SaveFileDialog at design-time it is easier to create a
SaveFileDialog at run-time.
Design-time
Figure 2
Adding a SaveFileDialog to a Form adds the following two lines of code.
Run-time
1. SaveFileDialog1.ShowDialog();
Once the ShowDialog method is called, you can browse and select a file.
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
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.
Default 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.
FilterIndex property represents the index of the filter currently selected in the file dialog
box.
1. SaveFileDialog1.FilterIndex = 2;
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;
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.
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
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
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.
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.
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.
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.
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.
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
The below code set a textbox width as 250 and height as 50 through source
code.
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.
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.
or
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
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
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).
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.
AnswerD
MCQ: Choose from the given options the one that can be overloaded
constructors
methods
parameters
operators
AnswerD
IL(Intermediate Language)
Both a and c
AnswerD
is potentially Unsafe
is memory consuming
AnswerB
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;
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
a) Status
b) Tool
c) Menu
d) Progress
a) procedure
b) debug
c)object
d)form
b) val
c) build In
d) balance
c) It is component oriented
a) toSbyte
b) tosingle
c) toString.
d) toInt64
b) define
c) elif
d) if
a)concat()
b) copy()
c)Compare
d) compare to
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
d) both b and c
d) all of above
a) catch
b) try
c)finally
d) thrown
a) a function
b) a boolean
c) a lnguage construct
d) an operator