Elance C# Test Answers 2015
·
Which statement do you use to stop loop
processing without a condition?
continue;
break;
jump;
Consider the following C# code: int x = 123;
if (x) { Console.Write("The value of x is nonzero."); } What happens
when it is executed?
It is invalid in C#.
Prints "The value of x is nonzero." to
the screen.
What do the following two lines of code
demonstrate: string Substring (int startIndex) string Substring (int
startIndex, int length) ?
method reflection
method overloading
operator overloading
The default value of a reference type is...
none of these
0
unknown
null
Given the following C# statement: int[] myInts
= { 5, 10, 15 }; What is the value of myInts[1]?
15
10
5
In order to create a filestream object in C#,
what do you need to include in your program?
using System.Strings
#include <System.IO>
using System.IO;
Exceptions can be handled in C# with a...
none of these
ON ERROR Resume NEXT statement
try catch finally block
Throw Exception
Choose the types of members which you can have
in your C# class?
fields
methods
all of these
constructors
Exceptions can be handled in Csharp with a...
Throw Exception
try catch finally block
ON ERROR Resume NEXT statement
none of these
If your Csharp class is called Cats, which
statement creates an object of type Cats?
Cats myCat = new Cats();
cats myCat = new cats();
Cats myCat = new cats();
Which C# debugging tools are available to you
with Visual Studio?
All of these
Breakpoints
Stepping through your code
The manifest of a C# assembly contains...
all of these
supported locales.
version information.
The purpose of the curly braces, { and }, in
C#:
None of these
is to mark the beginning and end of a logical block
of code.
is to mark function code to be used globally.
is to delineate the end of a statement to be
executed.
What type of memory management does Csharp
employ?
manual allocation
managed
Which of the following is not a built-in data
type in C#?
int
single
bool
string
The keyword used to include
libraries/namespaces in C# is:
include
import
use
using
Csharp provides a built in XML parser. What
line is needed to use this feature?
using System.Parser
using System;
using System.Xml;
using System.Strings
C# support what types of inheritance.
Interface inheritance
Implementation inheritance
All options.
Which classes are provided in C# for writing
an XML file?
XMLReader
XMLWriter
XMLCreation
Which statement is a convenient way to iterate
over items in an array?
switch
for
foreach
True or false: A class can implement multiple
interfaces
True
False
var x = default(DateTime); What is the
expected value of "x" ?
null
1/1/0001 12:00:00 AM
0
Compiler error
Exception will be thrown
A sealed class in C# means:
that you can create objects of that class type.
that the class cannot be used for inheritance.
derived classes can override some of the class
methods.
The foreach loop in C# is constructed as:
foreach (int i in collection)
there is no foreach loop in C#
foreach (collection as int i)
foreach (int i : collection)
for (int i : collection)
CSharp cannot be run without installing...
all .NET languages.
the Java Virtual Machine.
the Common Language Runtime.
What is the purpose of the following
statement: ~myClass() ?
It is a constructor for myClass instances.
It is a property called myClass.
It is the
destructor for myClass instances.
In C#, what would you use to output the
contents of a variable to the screen?
Console.Print() method
System.Write() method
Console.Write() method
What are the access modifiers available in C#?
public, private
protected, internal, private
public, protected, internal, private
public, protected, private
public, internal, private
Which class provides the best basic thread
creation and management mechanism for most tasks in Csharp?
System.Threading.ThreadPool
System.Runtime.Serialization
System.IO.Compression
The Code Document Object Model can be used
for...
all of these
allowing developers to create their own code
generation utilities.
developing automatic source code generators.
Which keyword would be used in a class
declaration to stop the class from being inherited?
out
sealed
static
extern
What is the purpose of the ref keyword in C#?
It allows you to change the reference address of
the variable.
It allows you to reference a variable value from
anywhere inside of your program.
It allows you to pass a parameter to a method by
reference instead of by value.
What is the result of the following
expression? int x = 100 / 0;
The system will throw a DivideByZeroException more
info
The system will throw a InvalidOperationException
x = NaN;
The system will throw a MathFormatException
x = null;
Where would you find the definition for the
Stack<T> class?
System.Data namespace
System.Collections.Specialized namespace
System.Collections.Generic namespace
Which of the following is an example of an
auto implemented property?
public string Name { get{ return m_name;} set{
m_name=value;} }
public string Name { }
public string Name { get; set; }
Which option below is an Operator?
All Options
Unary
Ternary
Binary
If you know that a method will need to be
redefined in a derived class,
you should declare it as virtual in the base class.
you should declare it as partial in the base class.
you should declare it as private in the base class.
What is the keyword to create a condition in a
switch statement that handles unspecified cases?
else(...)
if(...)
standard
default
finally
Can you change the value of a variable while
debugging a C# application?
No, code gets "locked-down" during
runtime.
Yes, if you are debugging via Visual Studio.NET,
just go to Immediate window.
An Indexer in C# allows you to index a
struct
class
Both class and struct
bool test = true; string result = test ?
"abc" : "def"; What is the value of result after execution?
It doesn't compile.
def
abc
abcdef
testabc
What is a jagged array in C#?
A multi-dimensional array with dimensions of
various sizes.
An array of singular dimension with an unknown
size.
A multi-dimensional array with dimensions of the
same size.
What does if((number <= 10) &&
(number >= 0)) evaluate to if number is -6?
True
False
When the protected modifier is used on a class
member,
no other class instances can access it.
the member can be accessed by derived class
instances.
it becomes the default access for all members of
the class.
Classes that can be used for reading / writing
files like TextReader, StreamWriter, File can be found in which namespace?
System.IO
System.Data
System.Stream
System.Text
System.DataAnnotations
Given the following statement: public enum
Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }. What
is the value of Monday?
1
"Monday"
none of these
0
An interface contains signatures only for
all of these
events
methods
properties
indexers
In C#, methods with variable number of
arguments:
don't exist
can be created using the "params" keyword
in argument list
can be created using the "..." signs in
argument list
Which of the following describes a C#
interface?
An interface is the UI presented to the user in an
application.
An interface allows you to define how a class will
be named.
An interface contains only methods and delegates.
Interface is a keyword that allows classes to
inherit from other classes.
An interface contains only the signatures of
methods, delegates or events.
What is the full name of the type that is
represented by keyword int?
System.Int64
Int32
System.Int32
System.Math.Int32
System.Int
A struct differs from a class in C#
in that a struct stores the value not a reference
to the value.
in that a class can be stored as either a reference
or a value.
in that a struct can contain implementation
inheritance.
During the class definition, inheritance in C#
is acomplished by putting which of the following:
":" sign
all of the answers are correct
keyword "inherits"
keyword "extends"
Which classes are provided in C# for
navigating through an XML file?
XMLReader
None of these
Both XMLDocument and XMLReader
XMLDocument
Valid parameter types for Indexers in C#
are...
integer
all of these
enum
string
The C# statement: using System; means...
all of these
create a namespace called system from the classes
defined in this file.
import the collection of classes in the System
namespace.
string is a mutable data type
True
False
Csharp provides an XML documentation comment
syntax by prefacing your comment lines with...
/*
//
///
In C# the System.String.Format method is used
for ....
Prettifying code snippets.
Coloring a input string with different colors to be
used for text visualization.
Making the specified string wordwrapped for text
visualization.
Replacing the format item in a specified string
with the string representation of a corresponding object.
Automatically formatting decimals into a currency
string representation. Ex: 1000 becomes $1 000
A static class in C# can only contain...
static members
both private and public members
both static and non-static members
none of these
Which of the following declares your Csharp
class as an attribute?
public class myAttribute : System.Attribute
public class myAttribute as System.Attribute
public class myAttribute
What is unique about an abstract class in C#?
You can only instantiate a reference to it.
You cannot inherit another class from it.
You cannot create an instance of it.
What does the following statement do?:
DateTime? startDate;
makes the variable a runtime only variable
allows you to create a reference to a value instead
of a stored value
allows you to set the variable startDate equal to
null
When the public modifier is used on a class,
no other classes can access it inside of your
program.
it becomes the default access for all classes in
your program.
the class can be accessed by external dll's.
Which keyword is needed to compile a method in
Csharp which uses pointers?
static
void
unsafe
If your C# class is a static class called
OutputClass, which contains public static void printMsg();, how would you call
printMsg?
OutputClass oc = new OutputClass(); oc.printMsg();
OutputClass.printMsg();
Both of these
You can attach a handler to an event by using
which operator?
++
+=
=
=>
->
The extern keyword is used to declare a method
which is...
implemented within the current project.
implemented externally.
implemented within one of the C# System classes.
What is the full name of the base type of all
the types in .NET?
System.Object
System
object
Object
System.object
Which of the following best describes this
class definition? : public class Foo<T> {}
This class extends the T class
It is a generic class
None of these
This class implements the T class
It is a class which contains one or more arrays
If you are overloading methods in a class the
methods must have...
none of these
the same parameter types.
the same name.
the same number of parameters.
In order for the following to compile: using
(CustomClass = new CustomClass()) { } CustomClass needs to implement which
interface?
IDisposable
ICustomAdapter
IUsing
Disposable
IMemoryManagement
The following line of code in C#:
IEnumerable<int> aList = new List<int>();
Legal
Illegal because the constructor of List cannot be
empty
Illegal because List does not implement IEnumerable
interface
Illegal because it is not allowed to create an
object of interface type
C# code is compiled in...
Common Intermediate Language, compiled in
CPU-specific native code the first time it's executed.
x86, x64 specific native code (or both), depending
on compilation options
Neutral bytecode, executed by the .Net virtual
machine.
Given: var foo = 7%2; what is the value of
foo?
0.035
7
3
3.5
1
In CSharp, what is the default member
accessibility for a class?
public
protected
private
Reflection is used to...
discover types and methods of assemblies on a
user's machine.
dynamically invoking methods on a user's machine.
viewing metadata.
all of these
In C#, if you would like to create a class
across multiple files, you should precede the class definition with...
the partial keyword
the internal keyword
the public keyword
Which attribute specifies a method to run
after serialization occurs?
OnSerialized
OnDeserializing
OnSerializing
OnDeserialized
How do you implement your own version of
ToString() method in your class?
private override string ToString() { }
public override string ToString() { }
public override ToString() { }
public string ToString() { }
public virtual string ToString() { }
How do you catch an exception indicating that
you are accessing data outside of the bounds of the array?
catch(ArrayTypeMismatchException ex)
catch(InsufficientExecutionStackException ex)
catch(ArrayIndexOutOfBounds ex)
catch(IndexOutOfRangeException ex)
Applications written in C# require the .NET
framework...
all of these
to be installed on the machine running the
application.
and the Visual Studio compiler to be installed on
the machine running the application.
A difference between a struct and a class is
that...
a struct acts like a value type.
structs support inheritance.
none of these
a struct is stored on the heap.
Which of the following is not a C# keyword?
as
in
is
of
if
In C#, a subroutine is called a ________.
Function
Method
Managed Code
Metadata
True or False? ushort is a signed integer.
False
True
Can you use pointers to manipulate memory in
C#?
No, C# objects are managed by garbage collection.
Yes, but only by using the unsafe keyword.
No, it is not a feature of C#.
What happens with the following lines? #region
Debug [block of code HERE] #endregion
You can visually expand or collapse the block of
code.
The entire block of code is executed just in debug
mode.
The entire block of code is commented.
Extension methods in C#...
are called as if they were instance methods
provide a way to add methods to existing types
without modifying them
all of the answers are correct
are a special kind of static method
provide a way to add methods to existing types
without new derived type
Which line is required in your Csharp
application in order to use the StringBuilder class?
using System.Strings
using System.Text;
using System;
Which is an example of a C# main method?
all of these
static void Main()
static int main()
none of these
What is: #if ?
Condition
Preprocessor directive
Compiler option
Invalid syntax
What will be printed on the console when the
following program is executed: public static void Main(string[] args) { bool
foo = new bool(); if (foo) Console.WriteLine("True"); else
Console.WriteLine("False"); }
"True" will be printed on the console
"False" will be printed on the console
A compile time error will happen because foo is not
initialized
A run time error will happen because foo is not
initialized
In the code below. public class Utilities :
System.Web.Services.WebService { [System.Web.Services.WebMethod] public string
GetTime() { return System.DateTime.Now.ToShortTimeString(); } }
[System.Web.Services.WebMethod] is an example of what?
Method Setting
Attribute
WebMethod
Functional Property
In the following array instantiation: string[]
names = new string[2]; , how many items can the array hold?
2
1
3
0
A struct can inherit from another struct or
class.
True
False
All of the following are valid c# keywords:
unchecked, extern,volatile, string, unsafe, implicit, virtual, stackalloc
False
True
What is the default visibility for members of
classes and structs in C#?
protected
internal
private
public
In the following statement: string[] words =
text.Split(delimiterChars); what is the function of delimiterChars?
Contains an array of characters which are to be
used to delimit the string.
Contains a string which is to be split into words.
Contains an array of characters to be split into
words.
C# provides an XML documentation comment
syntax by prefacing your comment lines with...
<!--
///
//
From which class do you need to derive to
implement a custom attribute?
System.Object
System.AttributeInfo
System.Attribute
System.Reflection.Attribute
System.AttributeUsage
C# is an object oriented language which does
not offer...
classes.
simple types.
global variables.
In C#, simple types like int, char, bool etc
has member functions.
false
true
The [Flags] attribute indicates that an enum
is to be used as a bit field. However, the compiler does not enforce this.
false
true
When dealing with currency calculations you
should always use what data type?
Int
Double
Int32
Float
Decimal
What is the purpose of the [STAThread]
attribute?
The [STAThread] makes it impossible to use multiple
threads in your application.
The [STAThread] makes it possible to use multiple
threads in your application.
The [STAThread] marks the application to use
Windows Forms components
The [STAThread] marks a thread to use the Single-Threaded
COM Apartment.
Converting a value type to reference type is
called....
Compilation
Boxing
Unboxing
Street magic
Typecasting
What description BEST suites the code below.
var Dictionary = new Dictionary<string,
int>(StringComparer.OrdinalIgnoreCase);
We're creating a standard dictionary object
Code wont compile
We're creating a case insensitive string dictionary
Which of the following statements about static
constructors are true?
The programmer cannot specify at what point in
their program a static constructor will be executed.
A static constructor cannot be called directly.
All answers are correct
A static constructor does not take access modifiers
or have parameters.
The expression: var ? count = 0;
Will create an implicit integer NULLABLE variable
Will give a compile time error.
Will create a dynamic NULLABLE variable
Will give a run time error.
Which keyword would be used in the class
definition if we did not want to create an instance of that class?
void
static
private
sealed
What's the best practice for enumerating all
the values of a Suit enum?
foreach (string suit in
Enum.GetNames(typeof(Suit))) { }
foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{ }
C# does not allow enum enumeration.
Will the following code compile? public class
CustomClass : IDisposable { }
Yes
No
The built-in string class in C# provides an
immutable object which means...
that the value of the string object can be changed
multiple times.
that the value of the string object can be set only
once.
all of these
What does the following statement do? #error
Type Mismatch
Generates an exception.
Generates an error which can be caught by a
try/catch block.
Generates a compiler error.
What will be the output of the following C#
code: int num = 1; Console.WriteLine(NUM.ToString());
1
Compile time error
None of the above
Undefined value
What does the params method keyword do?
all of these
Allows a variable number of parameters to be used
when a method is called.
Allows method parameters to be declared of any
type.
What does the Obsolete attribute do when used
in conjunction with a class?
All of these
It substitutes the newly specified class for the
obsolete class.
It generates an error/warning when the class is
used.
Consider the following statement: string str =
"abcdefg";. How would get the length of str?
int strlength = str.sizeOf()
int strlength = str.Length();
int strlength = str.Length;
How do you declare a generic method that takes
one parameter which must be a value type?
public void Test<T>(T t) where T : struct {
... }
public void Test<T>(T t) T is struct { ... }
public void Test<T : struct>(T t) { ... }
public void Test<struct T>(T t) { ... }
Which C# statement is equivalent to this: int
myInt = new int(); ?
int myInt;
int myInt = 0;
int myInt = NULL;
Proper way of defining an extension method for
a string class in C# is:
public static int WordCount(String, String str)
public static int WordCount(String str) : this
String
public static int WordCount(this String str)
public static int String.WordCount(String str)
public static int WordCount(String str) : String
True or False: We can create a sealed abstract
class in c#.
False
True
Can Abstract class support constructors ?
yes
no
partially
int[] myArray = new int[10]; What will be the
value of myArray[1]?
null
A null reference exception woulde be thrown unless
myArray[1] is first initialized to a value.
10
0
What is the result of the following code? var
a = 3; a = "hello"; var b = a; Console.WriteLine(b);
A run-time error
It outputs "hello"
A compilation error
It outputs "3"
Consider the following code: static void
Set(ref object value) { value = "a string"; } static void
Main(string[] args) { object value = 2; Set(ref value); } After the call to
"Set", what will the value in "value" be?
2
It won't compile.
"a string"
The primary expression for initializing an
anonymous object in C# is in the form of:
new {...}
None of the choices, strongly typed languages
cannot support anonymous objects
new T(...)
new T(...){...}
Which of the following is NOT a value type?
System.Int32
System.Char
System.Boolean
System.DateTime
System.String
Are bool and Boolean equivalent?
No, bool is a value type and Boolean is a reference
type
No, Boolean doesn't exist in C#
Yes
What is the keyword 'extends' used for?
is used to extend the functionality of an existing
class
'extends' keyword does not exist
is used to declare an implicit user-defined type
conversion operator
is used to access members of the base class from
within a derived class
What does this program output? public class
Program { struct Thing { public string Color { get; set; } } public static void
Main(params string[] args) { Thing one = new Thing { Color = "Red" };
Thing two = new Thing { Color = "Green" }; two = one; two.Color =
"Blue"; Console.WriteLine(one.Color); } }
Red
Green
Yellow
Magenta
Blue
What is the purpose of [Flags] attribute?
It does not exist in C#
Mark a class as obsolete.
Add metadata on elements, for documentation.
Allow values combination for enumeration (enums)
Anonymous functions can see the local
variables of the sourrounding methods.
False.
True.
Default DateTime.MinValue is "1/1/0001
12:00:00 AM"
True
False
What will happen if the requested type
conversion is not possible when using an "as" operator ?
System.InvalidCastException is thrown
null value is returned
Program will fail to compile
C# version is 2.0 or older returns NULL and newer
versions throws exception
What is the main difference between ref and
out parameters when being passed to a method?
Variables marked with "out" keyword
cannot be readonly whereas "ref" variables can be.
"out" parameters don't have to be
initialised before passing to a method, whereas "ref" parameters do.
"ref" parameters don't have to be
initialised before passing to a method, whereas "out" parameters do.
They are both same in every sense of the word.
Variables marked with "ref" keyword
cannot be readonly whereas "out" variables can be.
You need to create a custom Dictionary class,
which is type safe. Which code segment should you use?
public class MyDictionary : Dictionary<string,
string>
None of the listed answers
public class MyDictionary : IDictionary
public class MyDictionary {...} {
Dictionary<string, string> t = new Dictionary <string, string>;
MyDictionary dictionary = (MyDictionary) t; }
Given the method: static int Foo(int myInt,
params int[] myInts, int myOtherInt) { if (myInt > 1) return myOtherInt;
foreach (dynamic @int in myInts) myInt += @int; return myInt + myOtherInt; }
What will "Foo(1, 2, 3, 4, 5)" return?
Compiler error - parameter arrays must be the last
parameter specified.
15
5
10
Compiler error - The "dynamic" keyword
cannot be used to assign foreach iteration variables.
Which of the following is true of calling a
virtual method in a constructor:
Will call the derived method before the constructor
for the derived class has run.
Will generate a runtime error.
Will generate a compiler error.
Is better than an Initialize method because it
requires fewer lines of code.
In C# simple types like int, char and bool are
aliases for predefined classes in the System namespace.
False - they are not classes, they are structures
True - they are aliases for predefined classes in
the System namespace.
What namespaces are necessary to create a
localized application?
System.Data, System.Resources.
System.Globalization, System.Resources.
System.Resources, System.Localization.
Which of the following expressions give a
compile time error?
var d = new[] { 1, 1.5 , 2, 2.5, null, 4, 4.5 };
var myArray = new[,] { { "A",null, "C"
}, { "A", "B","C" }, { "C",
"D", "E" } };
var numbers = new[] { 1, 1.5, 2, 2.545454545454 };
If you have this in your configuration:
<appSettings> <add key="SomeSetting" value="1"
/> </appSettings> What does the output look like for this code: var someSetting
= ConfigurationManager.AppSettings["SomeSetting"];
Console.WriteLine("SomeSetting is {0} and is of type {1}",
someSetting, someSetting.GetType().Name);
SomeSetting is 1 and is of type string
SomeSetting is 1 and is of type String
SomeSetting is 1 and is of type object
SomeSetting is 1 and is of type Int32
SomeSetting is 1 and is of type int
Interfaces in C# cannot contain:
all of the answers are correct
events
implementation of methods
indexers
String a = "hello"; String b =
"hello"; var answer = object.ReferenceEquals(a, b); What is the value
of answer?
throws an exception
True
False
null
Consider the following code snippet: public
class A {...} public class B: A {...} public class C:B {...} then from the
following options, which one will give a compile time error?
A a = new B();
B b = new B();
B b= new A();
A a = new C();
C c = new C();
Which of the following is NOT reference type?
System.String
System.Exception
System.Type
System.Drawing.Point
A static member of a class is:
Something that can be accessed through an instance.
Shared by all instances of a class.
Neither of these
Both of these
In C#, "explicit" keyword is used
to:
explicitly cast types
"explicit" keyword doesn't exist in C#
create user-defined type conversion operator that
must be invoked with a cast
all of the answers are correct
In C#, "implicit" keyword is used
to:
create user-defined type conversion operator that
will not have to be called explicitly
all of the answers are correct
"implicit" keyword doesn't exist in C#
turn explicit casts into implicit ones
What does the following code do? string a =
"hello"; string b = null; string c = a + b; Console.WriteLine(c);
It outputs "hello"
It outputs "a + b"
It outputs "c"
It throws a NullReferenceException
It does not compile
int a = 5; for (int i = 0; i < 3; i++) { a
= a - i; } What is the value of the variable a after the code runs?
2
-1
0
1
3
True or False? Changing interfaces to base
classes with virtual methods can NOT improve performance of method invocations.
True
False
You are creating a class to compare a
specially formatted string. You need to implement the IComparable<string>
interface. Which code segment should you use?
public bool CompareTo(object other)
public int CompareTo(string other)
public bool Equals(string other)
public int Equals(object other)
What is wrong with this code: public enum
@enum : ushort { Item1 = 4096, Item2 = 8192, Item3 = 16384, Item4 = 32768,
Item5 = 65536, }
Invalid token ',' in class, struct, or enum.
Everything is wrong
Constant value '65536' cannot be converted to a
'ushort'
Keyword, identifier, or string expected after
verbatim specifier: @
Unexpected type declaration 'System.UInt16'
What does the following code output?
------------------------------------------------ using System; using
System.Collections.Generic; public class Program { public static void Main() {
var dictionary = new Dictionary<string,bool>(); bool isAlive = true;
dictionary.TryGetValue("Jaberwocky", out isAlive);
Console.WriteLine(isAlive); } }
It throws an exception
true
false
Jaberwocky
Polymorphism. LET: public class BaseClass {
public string DoWork() { return "A"; } } public class DerivedClass :
BaseClass { public new string DoWork() { return "B"; } } IF:
DerivedClass B = new DerivedClass(); BaseClass A = (BaseClass)B; A.DoWork();
What's the expected output?
A
Code won't compile
B
In C# "new" keyword is used to...
create objects and invoke constructors
restrict types that might be used as arguments for
a type parameter in a generic declaration
hide an inherited member from a base class member
All of the answers are correct
When can you assign a value to a readonly
field?
In the field constructor.
Neither of these
In the declaration of the field.
Both of these
When comparing strings, which of the following
Enum Type is utilized to specify the comparison culture and whether or not it
will ignore the case of the string?
StringComparer
StringFormat
StringComparison
StringUnit
In C#, difference between "new" and
"override" is:
"override" works in one-level
inheritance, "new" is multilevel
"new" explicitly hides a member inherited
from a base class
all of the answers are correct
"new" is used to overload a method,
"override" to override
What does the @ symbol do when used in C#
code?
Allows you to use reserved keywords as variable
names.
Both stops string literal escape sequences being
processed and allows you to use reserved keywords as variable names.
None of these
Stops string literal escape sequences being
processed.
C# delegates are object-oriented, type-safe,
they can be created in anonymous functions, they can reference static or
instance methods, and they do not know or care about the class of the
referenced method.
False, there is one incorrect statement mixed with
the correct ones.
True.
The following program is expected to run, and
after 500 ms write "OK" and exit, but fails to do that. How would you
fix this? class Test { int foo; static void Main() { var test = new Test(); new
Thread(delegate() { Thread.Sleep(500); test.foo = 255; }).Start(); while
(test.foo != 255) ; Console.WriteLine("OK"); } }
Wait 499 ms
Give thread a name
Make foo bool
Make foo volatile
Make Thread Priority to low
How many generations does the garbage
collector in .NET employ?
5
3
4
2
1
The main reflection methods to query
attributes are contained in the...
System.Reflection.GetCustomAttributes
System.Collections.Attributes
System.Reflection.MemberInfo class
Which answer is not a valid C# 4.0 variable
definition?
int[,] e = new int [2, 3];
var c = new int[1];
var b = new [] { 1 };
int[] a;
int[][] d = new int[1, 2];
How many string objects are created in this
piece of code: string first = "tick"; string second = first +
"tech"; second += "fly";
3
1
2
5
4
What is the size of a long on a 32 bit
operating system in C#?
Unsigned 32 bit integer
Signed 32 bit integer
Unsigned 64 bit integer
Signed 64 bit integer
The where condition for the generic definition
should be changed to ensure that the code will compile. class MyClass<V>
where V :class, IComparable { public void foo() { V aClass = new V(); } } class
Program { public static void Main(string[] args) { } } How should the where
condition be changed?
Remove IComparable from the generic where condition
Remove "class" from the generic where
condition
Add "new()" as the last generic where
condition
Impliment the interface IComparable. i.e define
CompareTo method inside MyClass
Cast expressions that you want to implicitly
convert.
True
False
Given the following code : void Main() { var x
= 123; Task t = new Task(()=>{ x++; }); t.Start();
Console.WriteLine(x.ToString()); } What is the expected value of x ?
124
123 or 124 (unpredected)
123
Given the following code: var result = 7/2;
what will be the value of result?
3.49999999
4
3.5
3
This code won't compile
In C#, what is the difference between:
"int[,] arrayName;" and "int[][] arrayName;"
"int[][] arrayName;" is not correct
declaration
"int[][] arrayName;" is multidimensional
array, while "int[,] arrayName;" is jagged array (array of arrays)
"int[,] arrayName;" is not correct
declaration
"int[,] arrayName;" is multidimensional
array, while "int[][] arrayName;" is jagged array (array of arrays)
There is no difference, they mean the same
What is the value of Status.TiredAndHungry?
public enum Status { Unknown = 0, Sick = 1, Tired = 2, Hungry = 4,
TiredAndHungry = Tired | Hungry }
5
3
6
4
This does not compile
Given code: var foo = 7; var bar = ++foo +
foo++; what is the value of bar?
17
16
15
18
14
False or True? Tuple is faster in every test
than KeyValuePair except in allocation performance.
False
True
Given the C# syntax for a method, attributes
modifiers return-type method-name(parameters ), what does the attribute
[Conditional("DEBUG")] on a method indicate?
The method will always execute when called
correctly.
The method will only execute if you compile with
the debug flag.
The method can only execute if the program has
defined DEBUG.
In the context of (A | B) and (A || B), the (A
|| B) boolean evaluation is known as what?
A "standard" evaluation
A "cross-circuit" evaluation
A "comparative" evaluation
A "short-circuit" evaluation
A "default" evaluation
What is the output of following program? class
Program { public enum Colors { Red = 1, Green = 2 } private static void Main()
{ Colors c = 0; Console.WriteLine(c); } }
It won't compile
Prints 0 in console
Prints Red in console
Prints 1 in console
It is possible to overload the "="
operator in C#.
False
True
What is the output of Console.WriteLine(10L /
3 == 10d / 3);?
True
False
Nothing, you will get a compiler error
What is the output of following program? class
Program { public enum Colors : System.Int32 { Red = 0, Green = 1 } private
static void Main() { Console.WriteLine(Colors.Green); } }
Prints Green in console
Throws runtime exception
It won't compile
Prints 1 in console
var a = new { name = "Frank", age =
22.5 }; var result = a.GetType() == new { name = "Bob", age = 64.1f
}.GetType(); what is the value of result?
False
True
Will not compile.
What will be the output of the following program:
#define DEBUG using System; using System.Diagnostics; class Program {
[Conditional("DEBUG")] public static bool Print() {
Console.WriteLine("Printed"); return true; } public static void
Main(string[] args) { Print(); } }
It will print "Printed" on the console
It will give a run time error because DEBUG is not
correctly defined
It will give a compilation error because the
conditional attribute is not valid
What is the result of following function?
public bool SomeTest(){ return "i like c#".ToUpper().Equals("I
LIKE C#"); }
Either true or false, depending on the current
culture
False, whatever the current culture
True, whatever the current culture
What will the following program print on the
console: static void Main(string[] args) { var i = typeof(void);
Console.WriteLine(i.Name); }
It will print "System.Object" on the
console
It will throw a run time exception
It will give a compile time error
It will print "Void" on the console
Which are not function members in a C# class?
Indexers
Fields
Operators
Destructors
Events
C# provides Finalize methods as well as
destructors, unlike Java. Which of the following is true about it?
That's not true, C# doesn't provide destructors.
Finalize method cannot be directly implemented,
however it is implicitly called by destructor, which can.
Destructor cannot be directly implemented, however
it is implicitly called by Finalize method, which can.
Finalize method is the destructor in C#.
Polymorphism. LET: public class BaseClass {
public virtual string DoWork() { return "A"; } } public class
DerivedClass : BaseClass { public override string DoWork() { return
"B"; } } IF: DerivedClass B = new DerivedClass(); BaseClass A =
(BaseClass)B; A.DoWork(); What's the expected output?
A
B
The code won't compile
What is wrong with this code? public struct
Person { public string FirstName { get; set; } public string LastName { get;
set; } public Person() { } public Person(string firstName, string lastName) {
this.FirstName = firstName; this.LastName = lastName; } } public struct
Customer : Person { public List<Order> Orders = new List<Order>();
}
'this' object cannot be used before all of its
fields are assigned to
Structs cannot contain explicit parameterless
constructors
All the answers
Structs cannot inherit from other classes or
structs
Structs cannot have instance field initializers
What will be the result of the following code:
float f = 1.5; Console.WriteLine(f);
A runtime error.
2
A compiler error.
1.5
1
abstract class BaseClass { public abstract
Color Color { get { return Color.Red; } } } sealed class Blues: BaseClass {
public override Color Color { get { return Color.Blue; } } } BaseClass test =
new Blues(); What is the result of test.Color ?
Blue
Compilation error
Red
null
InvalidOperationException
If A = true and B = false, how does [1.] (A |
B) differ from [2.] (A || B)
In [2.], B will be evaluated, in [1.] it wont
In [1.], B will be evaluated, in [2.] it won't be.
They're the same, just different ways of writing an
OR statement.
In [1.], A will be evaluated, in [2.] it wont
What is the expected output? static void
Main() { object o = -10.3f; int i = (int)o; Console.WriteLine(i); }
-10
Compile time error
Runtime exception (InvalidCastException)
0
10
Assuming the local system time offset is
UTC+5, what does the following program output? using System; public class
Program { public static void Main() { DateTime time1 = new DateTime(2000, 1, 1,
10, 45, 0, DateTimeKind.Local); DateTime time2 = new DateTime(2000, 1, 1, 10,
45, 0, DateTimeKind.Utc); TimeSpan span = time2 - time1;
Console.WriteLine(span); } }
00:05:00
-00:05:00
00:00:00
[Flags] enum Days{ None=0x0, WeekDays=0x1,
WeekEnd=0x2 } Days workingDays = Days.WeekDays | Days.WeekEnd; How do you
remove the Days.WeekEnd from the workingDays variable?
workingDays &= ~Days.WeekEnd;
workingDays |= !Days.WeekEnd;
workingDays &= !Days.WeekEnd;
workingDays &= ^Days.WeekEnd;
workingDays |= ~Days.WeekEnd;
Which of the following will set the process
return code to 1?
Application.ExitCode = 1
Console.ErrorLevel = 1,
Environment.Result = 1
void Main() { return 1; }
Environment.ExitCode = 1
What is wrong with the following code: static
class ImStatic { public event EventHandler StuffHappened; } class ReactsToStuff
{ public ReactsToStuff() { ImStatic.StuffHappened += React; } public void
React(object sender, EventArgs args) { Console.WriteLine("Stuff
happened"); } }
ReactsToStuff will never be collected by the
garbage collector after it is instantiated.
Static classes cannot declare events.
None of these.
A NullReferenceException will be thrown when
StuffHappened is fired if ReactsToStuff has already been collected by the
garbage collector.
Instance classes cannot handle events from static
classes
Can multiple catch blocks be executed?
No, once the proper catch code fires off, the
control is transferred to the finally block (if there are any)
Yes, catches excute in sequential order, then the
control is transferred to the finally block (if there are any)
Does return 10 as long; compile?
Yes
No, because 10 cannot be cast to long
No, because long is not a reference or nullable
type
No, because there is no as operator in C#
void Disagree(ref bool? maybe) { maybe = maybe
?? true ? false : maybe; } When calling this method, the value of the reference
parameter will be changed to:
true.
false.
null.
false if the previous value was true or false, true
if it was null.
The logical negation of the previous value, or true
if it was null.
If you would like to create a read-only
property in your C# class:
Mark the set method as private.
Neither of these
Both of these
Do not implement a set method.
What does the following code do? unchecked {
int i = Int32.MaxValue; int j = i; int product = i * j;
Console.WriteLine(product); }
Throws an OverflowException
Outputs "1"
Which of the following operators cannot be
overloaded?
=>
!=
<=
<<
>=
True or false? Types or members that have the
access modifier "protected internal" can be accessed in C# only from
types that SIMULTANEOUSLY satisfy these two conditions: 1) They are derived from
the containing class 2) They are in the current assembly
True
False
enum Score { Awful, Soso, Cancode } Given the
enum above, which statement(s) will generate a compiler error?
Score awful = 0;
Score soso = 1;
Score cancode = (Score)2;
All of them(because enum Score: int type was not
specified in declaration).
None of them(all three will compile and execute
just fine).
Which of these is NOT a way to create an int
array?
var b = new int[0];
var c = new [] { 0 };
var a = new int[];
int[] d = null;
var e = Array.CreateInstance(typeof(int), 1);
namespace DocGen { class Skills<T> {
public void Test(T t) { } } } According to C# standards and specifications, the
documentation generator ID string corresponding to "Test" method from
the code above should be:
"///<Method ret="void"
param="T" ns="DocGen" class="Skills"
public="true"> Test </Method>"
"M:DocGen.Skills.Test(ret void, param
System.Type):ContainsGenericParameters=true"
"M:DocGen.Skills.Test(T)"
"M:DocGen.Skills`1.Test(`0)"
All of them
What does the following statement do: delegate
double Doubler(double x); ?
Creates a signature for the method Doubler in the
delegate class.
Creates a type for the method Doubler.
Creates a method which may be called by any class.
Subscribe to:
Posts (Atom)