How Do I Port "synchronized" Functions From Visual J++ To C#?
Original Visual J++ code: public synchronized void Run()
{
// function body
}
Ported C# code: class C
{
public void Run()
{
lock(this)
{
// function body
}
}
public static void Main() {}
}
Can I Define A Type That Is An Alias Of Another Type (like Typedef In C++)?
Not exactly. You can create an alias within a single file with the "using" directive: using System; using Integer = System.Int32; // alias
But you can't create a true alias, one that extends beyond the file in which it is declared. Refer to the C# spec for more info on the 'using' statement's scope.
Is It Possible To Have A Static Indexer In C#?
No. Static indexers are not allowed in C#.
Does C# Support #define For Defining Global Constants?
No. If you want to get something that works like the following C code
#define A 1
use the following C# code: class MyConstants
{
public const int A = 1;
}
Then you use MyConstants.A where you would otherwise use the A macro.
Using MyConstants.A has the same generated code as using the literal 1.
Does C# Support Templates?
No. However, there are plans for C# to support a type of template known as a generic. These generic types have similar syntax but are instantiated at run time as opposed to compile time. You can read more about them here.
Does C# Support Parameterized Properties?
No. C# does, however, support the concept of an indexer from language spec. An indexer is a member that enables an object to be indexed in the same way as an array. Whereas properties enable field-like access, indexers enable array-like access. As an example, consider the Stack class presented earlier. The designer of this class may want to expose array-like access so that it is possible to inspect or alter the items on the stack without performing unnecessary Push and Pop operations. That is, Stack is implemented as a linked list, but it also provides the convenience of array access.
Indexer declarations are similar to property declarations, with the main differences being that indexers are nameless (the name used in the declaration is this, since this is being indexed) and that indexers include indexing parameters. The indexing parameters are provided between square brackets.
Does C# Support C Type Macros?
No. C# does not have macros. Keep in mind that what some of the predefined C macros (for example, __LINE__ and __FILE__) give you can also be found in .NET classes like System.Diagnostics (for example, StackTrace and StackFrame), but they'll only work on debug builds.
Can You Declare The Override Method Static While The Original Method Is Non-static?
No, you cannot, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.
Does C# Support Multiple Inheritance?
No, use interfaces instead.
Can You Override Private Virtual Methods?
No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.
What Is The Syntax For Calling An Overloaded Constructor Within A Constructor (this() And Constructorname() Does Not Compile)?
The syntax for calling another constructor is as follows
class B
{
B(int i)
{ }
}
class C : B
{
C() : base(5) // call base constructor B(5)
{ }
C(int i) : this() // call C()
{ }
public static void Main() {}
}
Why Do I Get A "cs5001: Does Not Have An Entry Point Defined" Error When Compiling?
The most common problem is that you used a lowercase 'm' when defining the Main method. The correct way to implement the entry point is as follows
class test
{
static void Main(string[] args) {}
}
What Does The Keyword Virtual Mean In The Method Definition?
The method can be over-ridden.
What Optimizations Does The C# Compiler Perform When You Use The /optimize+ Compiler Option?
The following is a response from a developer on the C# compiler team
We get rid of unused locals (i.e., locals that are never read, even if assigned).
We get rid of unreachable code.
We get rid of try-catch w/ an empty try.
We get rid of try-finally w/ an empty try (convert to normal code...).
We get rid of try-finally w/ an empty finally (convert to normal code...).
We optimize branches over branches
gotoif A, lab1
goto lab2
lab1
turns into: gotoif !A, lab2
lab1
We optimize branches to ret, branches to next instruction, and branches to branches.
How Can I Create A Process That Is Running A Supplied Native Executable (e.g., Cmd.exe)?
The following code should run the executable and wait for it to exit before continuing
using System;
using System.Diagnostics;
public class ProcessTest {
public static void Main(string[] args) {
Process p = Process.Start(args[0]);
p.WaitForExit();
Console.WriteLine(args[0] + " exited.");
}
}
Remember to add a reference to System.Diagnostics.dll when you compile.
What Is The Difference Between The System.array.copyto() And System.array.clone()?
The first one performs a deep copy of the array, the second one is shallow.
How Do I Declare Inout Arguments In C#?
The equivalent of inout in C# is ref. , as shown in the following example
public void MyMethod (ref String str1, out String str2)
{
...
}
When calling the method, it would be called like this
String s1;
String s2;
s1 = "Hello";
MyMethod(ref s1, out s2);
Console.WriteLine(s1);
Console.WriteLine(s2);
Notice that you need to specify ref when declaring the function and calling it.
Is There A Way Of Specifying Which Block Or Loop To Break Out Of When Working With Nested Loops?
The easiest way is to use goto
using System;
class BreakExample
{
public static void Main(String[] args)
{
for(int i=0; i<3; i++)
{
Console.WriteLine("Pass {0}: ", i);
for( int j=0 ; j<100 ; j++ )
{
if ( j == 10) goto done;
Console.WriteLine("{0} ", j);
}
Console.WriteLine("This will not print");
}
done
Console.WriteLine("Loops complete.");
}
}
What Is The Difference Between Const And Static Read-only?
The difference is that static read-only can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant. To expand on the static read-only case a bit, the containing class can only modify it: -- in the variable declaration (through a variable initializer).
-- in the static constructor (instance constructors if it's not static).
What Is The Difference Between System.string And System.stringbuilder Classes?
System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
What Is The Top .net Class That Everything Is Derived From?
System.Object.
Can You Allow Class To Be Inherited, But Prevent The Method From Being Over-ridden?
Yes, just leave the class public and make the method sealed.
From A Versioning Perspective, What Are The Drawbacks Of Extending An Interface As Opposed To Extending A Class?
With regard to versioning, interfaces are less flexible than classes. With a class, you can ship version 1 and then, in version 2, decide to add another method. As long as the method is not abstract (i.e., as long as you provide a default implementation of the method), any existing derived classes continue to function with no changes. Because interfaces do not support implementation inheritance, this same pattern does not hold for interfaces. Adding a method to an interface is like adding an abstract method to a base class--any class that implements the interface will break, because the class doesn't implement the new interface method.
What Is The Data Provider Name To Connect To Access Database?
Microsoft.Access.
Why Does My Windows Application Pop Up A Console Window Every Time I Run It?
Make sure that the target type set in the project properties setting is set to Windows Application, and not Console Application. If you're using the command line, compile with /target:winexe & not target:exe.
Describe The Accessibility Modifier Protected Internal?
It is available to derived classes and classes within the same Assembly (and naturally from the base class it is declared in).
How Do I Get Deterministic Finalization In C#?
In a garbage collected environment, it's impossible to get true determinism. However, a design pattern that we recommend is implementing IDisposable on any class that contains a critical resource. Whenever this class is consumed, it may be placed in a using statement, as shown in the following example
using(FileStream myFile = File.Open(@"c:temptest.txt", FileMode.Open))
{
int fileOffset = 0;
while(fileOffset < myFile.Length)
{
Console.Write((char)myFile.ReadByte());
fileOffset++;
}
}
When myFile leaves the lexical scope of the using, its dispose method will be called.
How Can I Get Around Scope Problems In A Try/catch?
If you try to instantiate the class inside the try, it'll be out of scope when you try to access it from the catch block. A way to get around this is to do the following
Connection conn = null;
try
{
conn = new Connection();
conn.Open();
}
finally
{
if (conn != null) conn.Close();
}
By setting it to null before the try block, you avoid getting the CS0165 error (Use of possibly unassigned local variable 'conn').
Why Do I Get An Error (cs1006) When Trying To Declare A Method Without Specifying A Return Type?
If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj)
How Do I Convert A String To An Int In C#?
Here's an example
using System;
class StringToInt
{
public static void Main()
{
String s = "105";
int x = Convert.ToInt32(s);
Console.WriteLine(x);
}
}
What Is The Difference Between A Struct And A Class In C#?
From language spec
The list of similarities between classes and structs is as follows. Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.
What Is The Difference Between The Debug Class And Trace Class?
Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
How Can You Overload A Method?
Different parameter data types, different number of parameters, different order of parameters.
When You Inherit A Protected Class-level Variable, Who Is It Available To?
Classes in the same namespace.
How Can I Get The Ascii Code For A Character In C#?
Casting the char to an int will give you the ASCII value: char c = 'f';
System.Console.WriteLine((int)c); or for a character in a string
System.Console.WriteLine((int)s[3]);
The base class libraries also offer ways to do this with the Convert class or Encoding classes if you need a particular encoding.
What's The Implicit Name Of The Parameter That Gets Passed Into The Set Method/property Of A Class?
What's Class Sortedlist Underneath?
A sorted HashTable.
What's The C# Equivalent Of C++ Catch (...), Which Was A Catch-all Statement For Any Possible Exception?
Original Visual J++ code: public synchronized void Run()
{
// function body
}
Ported C# code: class C
{
public void Run()
{
lock(this)
{
// function body
}
}
public static void Main() {}
}
Can I Define A Type That Is An Alias Of Another Type (like Typedef In C++)?
Not exactly. You can create an alias within a single file with the "using" directive: using System; using Integer = System.Int32; // alias
But you can't create a true alias, one that extends beyond the file in which it is declared. Refer to the C# spec for more info on the 'using' statement's scope.
Is It Possible To Have A Static Indexer In C#?
No. Static indexers are not allowed in C#.
Does C# Support #define For Defining Global Constants?
No. If you want to get something that works like the following C code
#define A 1
use the following C# code: class MyConstants
{
public const int A = 1;
}
Then you use MyConstants.A where you would otherwise use the A macro.
Using MyConstants.A has the same generated code as using the literal 1.
Does C# Support Templates?
No. However, there are plans for C# to support a type of template known as a generic. These generic types have similar syntax but are instantiated at run time as opposed to compile time. You can read more about them here.
Does C# Support Parameterized Properties?
No. C# does, however, support the concept of an indexer from language spec. An indexer is a member that enables an object to be indexed in the same way as an array. Whereas properties enable field-like access, indexers enable array-like access. As an example, consider the Stack class presented earlier. The designer of this class may want to expose array-like access so that it is possible to inspect or alter the items on the stack without performing unnecessary Push and Pop operations. That is, Stack is implemented as a linked list, but it also provides the convenience of array access.
Indexer declarations are similar to property declarations, with the main differences being that indexers are nameless (the name used in the declaration is this, since this is being indexed) and that indexers include indexing parameters. The indexing parameters are provided between square brackets.
Does C# Support C Type Macros?
No. C# does not have macros. Keep in mind that what some of the predefined C macros (for example, __LINE__ and __FILE__) give you can also be found in .NET classes like System.Diagnostics (for example, StackTrace and StackFrame), but they'll only work on debug builds.
Can You Declare The Override Method Static While The Original Method Is Non-static?
No, you cannot, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.
Does C# Support Multiple Inheritance?
No, use interfaces instead.
Can You Override Private Virtual Methods?
No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.
What Is The Syntax For Calling An Overloaded Constructor Within A Constructor (this() And Constructorname() Does Not Compile)?
The syntax for calling another constructor is as follows
class B
{
B(int i)
{ }
}
class C : B
{
C() : base(5) // call base constructor B(5)
{ }
C(int i) : this() // call C()
{ }
public static void Main() {}
}
OpenText Most Frequently Asked Latest C# Interview Questions Answers |
Why Do I Get A "cs5001: Does Not Have An Entry Point Defined" Error When Compiling?
The most common problem is that you used a lowercase 'm' when defining the Main method. The correct way to implement the entry point is as follows
class test
{
static void Main(string[] args) {}
}
What Does The Keyword Virtual Mean In The Method Definition?
The method can be over-ridden.
What Optimizations Does The C# Compiler Perform When You Use The /optimize+ Compiler Option?
The following is a response from a developer on the C# compiler team
We get rid of unused locals (i.e., locals that are never read, even if assigned).
We get rid of unreachable code.
We get rid of try-catch w/ an empty try.
We get rid of try-finally w/ an empty try (convert to normal code...).
We get rid of try-finally w/ an empty finally (convert to normal code...).
We optimize branches over branches
gotoif A, lab1
goto lab2
lab1
turns into: gotoif !A, lab2
lab1
We optimize branches to ret, branches to next instruction, and branches to branches.
How Can I Create A Process That Is Running A Supplied Native Executable (e.g., Cmd.exe)?
The following code should run the executable and wait for it to exit before continuing
using System;
using System.Diagnostics;
public class ProcessTest {
public static void Main(string[] args) {
Process p = Process.Start(args[0]);
p.WaitForExit();
Console.WriteLine(args[0] + " exited.");
}
}
Remember to add a reference to System.Diagnostics.dll when you compile.
What Is The Difference Between The System.array.copyto() And System.array.clone()?
The first one performs a deep copy of the array, the second one is shallow.
How Do I Declare Inout Arguments In C#?
The equivalent of inout in C# is ref. , as shown in the following example
public void MyMethod (ref String str1, out String str2)
{
...
}
When calling the method, it would be called like this
String s1;
String s2;
s1 = "Hello";
MyMethod(ref s1, out s2);
Console.WriteLine(s1);
Console.WriteLine(s2);
Notice that you need to specify ref when declaring the function and calling it.
Is There A Way Of Specifying Which Block Or Loop To Break Out Of When Working With Nested Loops?
The easiest way is to use goto
using System;
class BreakExample
{
public static void Main(String[] args)
{
for(int i=0; i<3; i++)
{
Console.WriteLine("Pass {0}: ", i);
for( int j=0 ; j<100 ; j++ )
{
if ( j == 10) goto done;
Console.WriteLine("{0} ", j);
}
Console.WriteLine("This will not print");
}
done
Console.WriteLine("Loops complete.");
}
}
What Is The Difference Between Const And Static Read-only?
The difference is that static read-only can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant. To expand on the static read-only case a bit, the containing class can only modify it: -- in the variable declaration (through a variable initializer).
-- in the static constructor (instance constructors if it's not static).
What Is The Difference Between System.string And System.stringbuilder Classes?
System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
What Is The Top .net Class That Everything Is Derived From?
System.Object.
Can You Allow Class To Be Inherited, But Prevent The Method From Being Over-ridden?
Yes, just leave the class public and make the method sealed.
From A Versioning Perspective, What Are The Drawbacks Of Extending An Interface As Opposed To Extending A Class?
With regard to versioning, interfaces are less flexible than classes. With a class, you can ship version 1 and then, in version 2, decide to add another method. As long as the method is not abstract (i.e., as long as you provide a default implementation of the method), any existing derived classes continue to function with no changes. Because interfaces do not support implementation inheritance, this same pattern does not hold for interfaces. Adding a method to an interface is like adding an abstract method to a base class--any class that implements the interface will break, because the class doesn't implement the new interface method.
What Is The Data Provider Name To Connect To Access Database?
Microsoft.Access.
Why Does My Windows Application Pop Up A Console Window Every Time I Run It?
Make sure that the target type set in the project properties setting is set to Windows Application, and not Console Application. If you're using the command line, compile with /target:winexe & not target:exe.
Describe The Accessibility Modifier Protected Internal?
It is available to derived classes and classes within the same Assembly (and naturally from the base class it is declared in).
How Do I Get Deterministic Finalization In C#?
In a garbage collected environment, it's impossible to get true determinism. However, a design pattern that we recommend is implementing IDisposable on any class that contains a critical resource. Whenever this class is consumed, it may be placed in a using statement, as shown in the following example
using(FileStream myFile = File.Open(@"c:temptest.txt", FileMode.Open))
{
int fileOffset = 0;
while(fileOffset < myFile.Length)
{
Console.Write((char)myFile.ReadByte());
fileOffset++;
}
}
When myFile leaves the lexical scope of the using, its dispose method will be called.
How Can I Get Around Scope Problems In A Try/catch?
If you try to instantiate the class inside the try, it'll be out of scope when you try to access it from the catch block. A way to get around this is to do the following
Connection conn = null;
try
{
conn = new Connection();
conn.Open();
}
finally
{
if (conn != null) conn.Close();
}
By setting it to null before the try block, you avoid getting the CS0165 error (Use of possibly unassigned local variable 'conn').
Why Do I Get An Error (cs1006) When Trying To Declare A Method Without Specifying A Return Type?
If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj)
How Do I Convert A String To An Int In C#?
Here's an example
using System;
class StringToInt
{
public static void Main()
{
String s = "105";
int x = Convert.ToInt32(s);
Console.WriteLine(x);
}
}
What Is The Difference Between A Struct And A Class In C#?
From language spec
The list of similarities between classes and structs is as follows. Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.
What Is The Difference Between The Debug Class And Trace Class?
Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
How Can You Overload A Method?
Different parameter data types, different number of parameters, different order of parameters.
When You Inherit A Protected Class-level Variable, Who Is It Available To?
Classes in the same namespace.
How Can I Get The Ascii Code For A Character In C#?
Casting the char to an int will give you the ASCII value: char c = 'f';
System.Console.WriteLine((int)c); or for a character in a string
System.Console.WriteLine((int)s[3]);
The base class libraries also offer ways to do this with the Convert class or Encoding classes if you need a particular encoding.
What's The Implicit Name Of The Parameter That Gets Passed Into The Set Method/property Of A Class?
Value. The data type of the value parameter is defined by whatever data type the property is declared as.
What's Class Sortedlist Underneath?
A sorted HashTable.
What's The C# Equivalent Of C++ Catch (...), Which Was A Catch-all Statement For Any Possible Exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.
What's A Delegate?
A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.
What's A Multicast Delegate?
It’s a delegate that points to and eventually fires off several methods.
How's The Dll Hell Problem Solved In .net?
Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
What's A Satellite Assembly?
When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
What's The Difference Between // Comments, /* */ Comments And /// Comments?
Single-line, multi-line and XML documentation comments.
What's The Difference Between <c> And <code> Xml Documentation Tag?
Single line code example and multiple-line code example.
Post a Comment