About us
Home
Contact
Guestbook
Nature page
Technlogy news
Great Saints in Tamilnadu
Important days
C# interview questions and answers page
what is meant by meditation
C# interview questions and answers page

http://en.csharp-online.net/CSharp_FAQ:_What_is_.NET

 

 

 

In above website we are getting the details:

 

 

 

 

What is .NET?

.NET is a runtime platform created by Microsoft Corporation. .NET comprises a virtual execution environment—garbage collection, Just-In-Time (JIT), memory safety, strong versioning, type safety, etc.—and a runtime library. .NET is the soul of the Microsoft strategy for the latest and future Windows platforms.

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_What_is_.NET"

Must the framework be installed to run .NET applications?

The .NET Framework is required in order to run managed applications. That is, the .NET Framework must be installed on the computer before a managed application can be executed. This requirement is in effect even when precompiled code—e.g. ngen—is executed.

Similarly, the Win32 libraries must be present in order to run Windows applications.

Alternatively, there are software products which can build all the needed components of the .NET Framework into the application itself: Since the application includes the required .NET components, the .NET Framework need not be installed separately. The following are some of the products available which can bundle the necessary .NET components with the application:

*       RemoteSoft linker and mini-deployment tool

*       Thinstall Studio

*       Xenocode

There are advantages and disadvantages to using such products; but, the technicalities will not be covered here.

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_Must_the_framework_be_installed_to_run_.NET_applications"

Must the framework be installed to run .NET applications?

The .NET Framework is required in order to run managed applications. That is, the .NET Framework must be installed on the computer before a managed application can be executed. This requirement is in effect even when precompiled code—e.g. ngen—is executed.

Similarly, the Win32 libraries must be present in order to run Windows applications.

Alternatively, there are software products which can build all the needed components of the .NET Framework into the application itself: Since the application includes the required .NET components, the .NET Framework need not be installed separately. The following are some of the products available which can bundle the necessary .NET components with the application:

*       RemoteSoft linker and mini-deployment tool

*       Thinstall Studio

*       Xenocode

There are advantages and disadvantages to using such products; but, the technicalities will not be covered here.

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_Must_the_framework_be_installed_to_run_.NET_applications"

Does .NET run only on Windows?

Even if you do not operate a machine running the Windows operating system, it may still be possible to run .NET. There are several open source projects to create Common Language Runtime (CLR) systems which function on other operating systems, e.g., BSD, Linux.

Two prominent open source projects are:

*       Mono - open source multi-platform system

*       ROTOR - Microsoft Shared Source implementation for FreeBSD, Mac OS X 10.2, and Windows XP.

Since .NET is the Microsoft trademark for it's Windows implementation of the CLR and related technologies, the preceding projects are not—strictly speraking—.NET implementations. And, these open source implementations may not cover all the framework and related libraries available in .NET. On the other hand, they may contain libraries which are not found in .NET. However, these implementations allow the compiling and running of C# programs on non-Windows platforms.

What do all the .NET acronyms mean?

.NET and related technologies are replete with new acronyms, for example CLI, CLR, and CLS. There is no need to learn them in advance. Just learn them as they are encountered in your readings.

But, here are a few of the more common acronyms just to get you started:

Acronym

Definition

CIL (Common Intermediate Language)

The language to which all .NET languages compile. CIL is the equivalent of Java bytecode.

CLI (Common Language Infrastructure)

CLI comprises the CIL, CLR, CLS, and CTS.

CLR (Common Language Runtime)

The .NET runtime environment itself including managed program execution and container services.

CLS (Common Language Specification)

Conventions designed to promote language interoperability.

CTS (Common Type System)

The language-neutral type system found in the CLI.

IL (Intermediate Language)

A common abbreviation for CIL above.

VES (Virtual Execution System)

VES is the environment for executing managed code.

Are .NET generics like C++ templates?

No, .NET generics are not like C++ templates.

Although .NET 2.0 generic types share a similar syntax with C++ templates, there are substantial differences. Whereas .NET generic types are instantiated at runtime, C++ templates are created at compile time. Significantly, .NET generic types can be inspected using reflection of metadata. And, generic member access on the type paramater is verified from the constraints placed on the type parameter. On the other hand, template member access is verified on the type argument after instantiation. Generally, depending upon the implementation, template code is faster and leaner than an equivalent generic alternative.

Beginning with Visual Studio 2005, C#, Managed C++, and Visual Basic .NET all have Common Language Runtime (CLR) support for generics

How enforce coding guidlelines for custom .NET assemblies?

Best practices means different things to different developers. But, custom .NET assemblies can be made to conform with the coding guidelines backed by Microsoft using FxCop.

FxCop can load a .NET binary and run a battery of tests against it to determine how the assembly measures up against the Microsoft coding standards. These standards—and best practices—are obeserved in the Base Class Libraries (BCL). FxCop allows custom rules to be created and existing rules to be ignored where desired.

Download free FxCop.

"FxCop is an application that analyzes managed code assemblies (code that targets the .NET Framework common language runtime) and reports information about the assemblies, such as possible design, localization, performance, and security improvements. Many of the issues concern violations of the programming and design rules set forth in the Design Guidelines for Class Library Developers, which are the Microsoft guidelines for writing robust and easily maintainable code by using the .NET Framework.

"FxCop is intended for class library developers. However, anyone creating applications that should comply with the .NET Framework best practices will benefit. FxCop is also useful as an educational tool for people who are new to the .NET Framework or who are unfamiliar with the .NET Framework Design Guidelines.

"FxCop is designed to be fully integrated into the software development cycle and is distributed as both a fully featured application that has a graphical user interface (FxCop.exe) for interactive work, and a command-line tool (FxCopCmd.exe) suited for use as part of automated build processes or integrated with Microsoft Visual Studio .NET as an external tool."

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_How_enforce_coding_guidelines_for_custom_.NET_assemblies"

Is there a .NET equivalent to regsvr32?

Whereas Regsvr32 is used on unmanaged COM libraries, Regasm is used on managed .NET libraries.

Regsvr32 is a command-line tool for registering .dll files as command components in the Windows registry.

Regasm—the assembly registration tool provided with the .NET System Development Kit (SDK)—reads assembly metadata and adds necessary entries to the Windows registry, thus allowing COM clients to create .NET Framework classes transparently. After a class has been registered, any COM client can use it as though the class were a COM class. The class will be registered only once when the assembly is installed. Instances of assembly classes cannot be created from COM until they are registered.

There are two related utilities with functions similar to those of Regasm. Gacutil can be used when there are no COM exports. Installutil can be used for a Windows service.

To programmatically register an assembly, refer to the RegistrationServices class and ComRegisterFunctionAttribute.

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_Is_there_a_.NET_equivalent_to_regsvr32"

How call a method using a name string?

Reflection enables an application to locate the type containing the method, find the method within that type, and invoke the method—all starting with having only the method name in a string.

The following is a simple—reflection can do much more than this—example that finds a public method which passes no parameters and returns void:

using System;
using System.Reflection;
 
class CallMethodByName
{
   string name;
    
   CallMethodByName (string name)
   {
      this.name = name;
   }
    
   public void DisplayName()      // method to call by name
   {
      Console.WriteLine (name);   // prove we called it
   }
    
   static void Main()
   {
      // Instantiate this class
      CallMethodByName cmbn = new CallMethodByName ("CSO");
 
      // Get the desired method by name: DisplayName
      MethodInfo methodInfo = 
         typeof (CallMethodByName).GetMethod ("DisplayName");
 
      // Use the instance to call the method without arguments
      methodInfo.Invoke (cmbn, null);
   }
}

Are there free .NET decompilers?

Both open source and commercial obfuscators are available.

*                   Anakrino is an older .NET decompiler which is a bit long in the tooth now.

*                   Reflector for .NET: Reflector is a .NET decompiler sporting a great user interface and quick, effective decompiles. The optional FileDisassembler add-in writes an assembly which has been decompiled with Reflector to a source files which can be loaded, edited recompiled, and searched.

 

How good are Java decompilers and .NET decompilers?

.NET applications are easily decompiled—as are all languages which compile to an intermediate code. All .NET and the Java language feature an expressive file syntax for executable code— Java bytecode and .NET Microsoft Intermediate Language (MSIL). Unlike binary machine code, intermediate files contain algorithms, identifiers, and other application items which can be read and understood as easily as an assembly code listing.

How protect my code against decompilation?

[edit]

Or, how protect .NET code from reverse engineering?

.NET languages are compiled into Intermediate Language (IL). IL is easily decompiled back into a .NET language. Therefore, many developers worry about the possible theft of their intellectual property (IP) in the form of a .NET assembly.

To guard against decompilation, many developers resort to obfuscation. Obfuscators work by scrambling the IL code around into an "unnatural" form—an inefficient and unreadable form which would not be produced by a .NET compiler. Heavily obfuscated code may incur a severe performance penalty. Obfuscators may also introduce subtle or not so subtle bugs into the application. While obfuscation may help deter amateur decompilers, professional IP thieves will only be slowed down.

.NET decompilers are designed to read an executable file—e.g. .NET .exe or .dll file—and create a source file which can be read, edited, and compiled.

*                   Dotfuscator Community Edition is a free, community version of a commercial obfuscator

What about .NET decompilers that allow code to be submitted from browsers?

We recommend that .NET decompilers that allow code to be submitted directly via Web browsers not be used. Such decompiler Web sites might keep a copy of the source code submitted by programmers! Best practice is to download a .NET decompiler and run it locally on your own machine

How start another program from .NET?

In order to initiate a new process using the .NET Framework, use the Process.Start method. More complex start-up parameters can be specified using the ProcessStartInfo class. This class allows output redirection, specification of command line parameters, etc.

Both the Process and ProcessStartInfo classes reside in the System.Diagnostics namespace.

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_How_start_another_program_from_.NET"

How ensure that only one instance of an application will run?

Often, it is necessary to be sure that only a single instance of an application will be running at a time. Examples include applications which control resources. There is a design pattern designed specifically for this purpose called the Singleton design pattern.

Another way of accomplishing this is by using a named mutex. The following example illustrates the creation of a mutex:

bool instantiated;
 
Mutex mutex = new Mutex
   (false, "Local" + aUniqueID, out instantiated);
 
// If instantiated is true, this is the first instance 
// of the application; else, another instance is running. 

The mutex must be local—meaning it exists in the current user session. If the mutex were not local, users could share the mutex. Thus, two different users could not be running the program at the same time. Unlike various examples to be found on the Web, this sample code does not contain a call to a ReleaseMutex method. Because, the mutex will be released automatically when the process dies. If this is not the desired behavior, add such a method.

The mutex will not be garbage collected. Therefore, if a local variable is only used near the beginning of a method, the Garbage Collector (GC) may ignore it when determining which variables are garbage collection "roots" if that part of the method has already been executed. This can result in the mutex being released earlier than expected. To prevent premature release, make a call to:

GC.KeepAlive (mutex);

at the end of the Main method.

Or, use a static variable to hold the mutex. That ensures that the mutex will not be garbage collected until the AppDomain is unloaded. With this strategy, even should the Main terminate, there will not be any problems if other threads are running.

Another strategy is to "listen" on a local port. Since only one process can listen to a particular port, this fact can be exploited to ensure that only one instance of your application is running. But, there will be problems if another application tries to use that port for any purpose. Also, this strategy provides a communication channel between the initial instance and the new instance. For example, the new instance might want to tell the initial instance to open a user-requested file. This could be accomplished using the socket.

 

How to read files with accented characters?

Actually, this can be a large, complex topic. However, textual information—e.g. as stored in a file or sent over a network—is encoded; that is, the characters are converted into bytes according to some scheme. Therefore, bytes must be decoded to retrieve the information as characters again.

Normally, the encoding and decoding schemes must match or errors may result. And, this is the typical cause of decoding failures in which "extended" characters appear improperly decoded. (They may appear as empty boxes or as other incorrect characters.)

 

How get assembly attributes at runtime?

The majority of assembly-wide attributes—usually specified in AssemblyInfo.cs—can be retrieved using Assembly.GetCustomAttributes. For example, code such as the following can be used to get the assembly title:

Assembly thisAssembly = this.GetType().Assembly;

object[] attributes = thisAssembly.GetCustomAttributes

   (typeof(AssemblyTitleAttribute), false));

if (attributes.Length == 1)

{

   Console.WriteLine (((AssemblyTitleAttribute) attributes[0]).Title);

}

Notice that AssemblyVersionAttribute becomes a part of the assembly name, which can be accessed via the Assembly.GetName method. The version can be accessed via the name with the Version property. For example:

Assembly thisAssembly = this.GetType().Assembly;

Console.WriteLine (thisAssembly.GetName().Version);

Why does .NET make arithmetic errors?

If you are new to computer arithmetic, you may have a few surprises coming. Computer arithmetic is necessarily done in binary (base 2); so, many floating point numbers can only be approximated in the binary. All runtime systems face these limitations, not just the .NET Common Language Runtime (CLR).

The following is a simple example:

double d = 0.1;

The value 0.1 must be stored in a variable of type double. But, that decimal value has no precise equivalent in binary. So, a value is stored which is as close to 0.1 as can be represented in a (binary) double type; but, the value is not exactly 0.1.

This potential problem exists for both double and float types where decimal fractions must be represented in binary.

 

How display int as a binary number, a string of 0s and 1s?

The Convert class has an overload of the static ToString() method which accepts two ints and returns a string containing the specified number in the specified base.

For example, the following source code:

Console.WriteLine (Convert.ToString (128, 2) );

will result in the following output:

 

 Convert int to binary string example (program output)

10000000

Should calling Initialize() on a reference type array fill it with objects?

The Initialize() method of a System.Array class instance is designed to initialize value type arrays to their default values. But, it does not work on reference type arrays.

Actually, Initialize() is not designed for C# value type structs; because, C# structs cannot have default constructors which Initialize could call. Common Language Runtime (CLR) value types may have parameterless constructors; but in C#, there is no practical method of creating such a type.

What compression and zipping capabilities does .NET have?

As of version 1.1, the .NET Framework did not contain any general purpose compression libraries. However, there are numerous third-party libraries available. SharpZipLib is a popular, free, open source compression library which can be used in commercial applications.

As of version 2.0, the .NET Framework contains a few compression routines. They can be found in the System.IO.Compression namespace. However, it does not provide support for .zip files proper.

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_What_compression_zipping_capabilities_has_.NET"

How convert a string type to an int type?

For general type conversions, consult the System.Convert method first. System.Convert features static methods for most everyday type conversions.

When converting from a type String, determine whether the type to be converted to has a Parse method. In fact, the method name may be derived from the word parse. For example, the DateTime.ParseExact method can be used to convert from a type String to a type DateTime.

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_How_convert_string_to_int"

What is the difference between Convert.ToInt32(string) and Int32.Parse(string)?

Convert.ToInt32(string) and Int32.Parse(string) yield identical results except when the string is actually a null. In this case, Int32.Parse(null) throws an ArgumentNullException; but, Convert.ToInt32(null) returns a zero.

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_What_is_the_difference_between_Convert.ToInt32_and_Int32.Parse%3F"

How create an instance of a type using only its name?

Firstly, get a Type reference for the type. If the type to be instantiated is in either the current assembly or mscorlib, simply use Type.GetType(name). If the type is in a different assembly, there are two options: either call Type.GetType passing in the full type name including assembly information; or, find or load the assembly then call Assembly.GetType(name) using the assembly reference.

With the Type reference, use either Activator.CreateInstance(type) to create an instance; or, call Type.GetConstructor to get a specific constructor which can then be used instantiate by calling Invoke.

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_How_create_an_instance_of_a_type_using_only_its_name"

What is the easiest way to fetch a Web page in .NET?

The System.Net.WebRequest class offers a simple, easy-to-use method of retrieving Web pages. The WebRequest class features many options including asynchronous downloading and numerous properties for both the request and response.

For basic, simplified applications, the System.Net.WebClient class can be a viable alternative to the WebRequest class.

The following example illustrates a basic application of the System.Net.WebRequest class:

using System.IO;

using System.Net;

using System.Text;

 

...

 

string url = "http://en.csharp-online.net/";

 

WebRequest request = WebRequest.Create (url);

 

// For HTTP, cast the request to HttpWebRequest

// allowing setting more properties, e.g. User-Agent.

// An HTTP response can be cast to HttpWebResponse.

 

using (WebResponse response = request.GetResponse())

{

   // Ensure that the correct encoding is used.

   // Check the response for the Web server encoding.

   // For binary content, use a stream directly rather

   // than wrapping it with StreamReader.

 

   using (StreamReader reader = new StreamReader

      (resp.GetResponseStream(), Encoding.UTF8))

   {

       string content = reader.ReadToEnd();

       // process the content

   }

}

Am I missing an assembly reference?

Most developers encounter the following error frequently:

 

 Error (program output)

The type or namespace '<namespace name>' does not exist in

the class or namespace '<parent namespace>' (are you missing an

assembly reference?)

 

 

This error message indicates that a reference must be added in the project to an assembly where that namespace is defined.

[edit]

Adding a reference using Visual Studio .NET

When using Visual Studio .NET, follow these steps to add a reference:

1.     Right click on the References folder on your project.

2.     Select Add Reference.

3.     Select the .NET tab; or, select the Browse button if not a .NET Framework assembly.

4.     Double click the assembly containing the namespace named in the error message.

5.     Press the OK button.

[edit]

Adding a reference from the Windows command line

When using the command line, use the /r: or /reference: option. Here is an example:

csc.exe /reference:System.Drawing.dll FontDisplayAppl.cs

Upon recompilation, the error message will have magically disappeared!

To find the assembly in which a namespace is defined, check the documentation. Identify a type in the namespace that must be used. Every type in the .NET Framework has an "About" page which gives a brief overview, some basic type information, and—hopefully—sample source code.

Near the bottom of the "Overview" section, find the "Requirements" section. It contains a Namespace member which specifies the namespace to which the type belongs. Also, this section lists to which assembly a type belongs as well as which assembly the application must reference.

For instance, if an application uses Font types, look up Font in the .NET Framework documentation using the Index tab. Note that the Font type is in the System.Drawing namespace and its assembly is System.Drawing.dll.

Are C# constructors inherited?

No. C# constructors cannot be inherited.

If constructor inheritance were allowed, then necessary initialization in a base class constructor might easily be omitted. This could cause serious problems which would be difficult to track down. For example, if a new version of a base class appears with a new constructor, your class would get a new constructor automatically. This could be catastrophic.

How can one constructor call another?

To call one C# constructor from another, before the body of the constructor, use either:

: base (parameters)

to call a constructor in the base class; or:

: this (parameters)

to call a constructor in this class.

The following examples illustrate how to call one constructor from another.

public class Supervisor : Employee

{

   public Supervisor (int vacationDays) : base (vacationDays)

   {

      //Add more statements here.

   }

}

In the prededing example, the base class constructor is called before the constructor block is executed. The base keyword is usable with or without parameters. Any constructor parameters can be used either as part of an expression or as parameters to base.

public class Employee

{

   public Employee(int weeklyOvertime)

   {

      overtime = weeklyOvertime;

   }

 

   public Employee (int overtimeRate, int numberHours)

      : this (overtimeRate * numberHours)

   {

      //Add more statements here.

   }

}

Are constructors the same in C++ and C#?

Although there are strong similarities between C# constructors and C++ constructors, there are, also, some significant differences.

Firstly, C# supports constructor chaining—one constructor can call another as in the following example:

class Employee

{

   public Employee (string name, int salary) { ... }

 

   public Employee (string name) : this (salary, 0) {}

 

   public Employee() : this ("", 0) {}

}

Secondly, virtual method calls within a constructor are directed to the most derived implementation.

Thirdly, error handling is a bit different. When an exception occurs during C# object construction, the destructor—finalizer—will be called. This behavior differs from C++ behavior in which the destructor is not called if construction is interrupted.

Lastly, C# has static constructors. A static constructor for a class executes before the first instance of the class is created.

Interestingly, some C# developers—like some C++ developers—prefer the factory pattern to constructors.

Are destructors the same in C++ and C#?

No. Although, they look the same, C++ and C# destructors are—in fact—very different. C# destructor syntax using the familiar tilde (~) character is but a compiler cover for an override of the Finalize method of System.Object.

This Finalize method is called by the garbage collector (GC) when it discovers that an object is not being referenced. Afterwards, the garbage collector frees the memory associated with the object. The difference is that the garbage collector does not guarantee when this procedure will happen. In fact, it may be a long time after the application has finished with the object before the garbage collector takes action. This uncertainty of timing is dubbed non-deterministic finalization. Accordingly, C# destructors are unsuitable for releasing scarce resources, e.g. database connections, file handles, etc.

To achieve deterministic destruction, a class must contain a method dedicated to that purpose. Typically, a class will implement the IDisposable interface. And, the Dispose() method of the object must be called when the object is no longer needed. The 'using' keyword of C# can be used to write a clean Dispose() method.

How call a virtual method from a constructor or destructor?

In C++, objects are constructed from base class to derived class. This means that when the base class constructor is running the object is effectively a base object. So, C++ virtual method calls are directed to the base class implementation.

In .NET on the other hand, the derived constructor is executed first. This means the object will be a derived object; and, virtual method calls are directed to the derived implementation.

The C# compiler inserts a call to the base class constructor at the beginning of any derived constructor in order to maintain OO semantics, i.e. that the base class constructor is called first.

In a similar fashion, when C# destructors call virtual methods, virtual method calls from a base destructor are directed to the derived implementation.

Therefore, in C#, a virtual method can be called from a constructor or destructor. But, usually, it is a bad idea. .NET object construction is very different from C++ object construction; and, virtual method calling is affected.

 

How do destructors work in C#?

A destructor is a method that is called when an object is destroyed—it's memory is marked unused. C++ destructors are used to free up memory and other resources and to perform housekeeping tasks. In .NET, the Garbage Collector (GC) performs much of this type of work automatically. Generally, rather than define a destructor for manual cleanup, let the Common Language Runtime (CLR) handle it.

In C#, the Finalize method performs the operations that a standard C++ destructor might perform. Finalizers are similar to destructors except that it is not guranteed that they will be called by the CLR.

Here is a sample finalizer specification using the C++ destructor syntax which places a tilde (~) symbol before the class name:

class Test

{

   ~Test()

   {

      ...

   }

 

   public static void Main() {}

}

When defining a C# finalizer, it is not named Finalize. However, finalizers do override object.Finalize(), which is called during the garbage collection process.

How enforce constructor correctness in C# ?

Constructor correctness cannot be enforced in C#. Because, the Common Language Infrastructure (CLI) does not define constructor correctness. For instance, it cannot be specified that a method must not modify an argument being passed in to the method. Also, it cannot be specified that a method does not modify the object upon which it acts.

 

Why must struct constructors have at least one argument?

The .NET Common Language Runtime (CLR) does not guarantee that parameterless constructors will be called. If structs were permitted to have default, parameterless constructors, the implication would be that default constructors would always be called. Yet, the CLR makes no such guarantee.

For instance, an array of value types will be initialized to the initial values of its members—i.e., zero for number type primitive members, null for reference types, and so forth—and not to the values provided in a default constructor. This feature makes structs perform better; because, constructor code need not be called.

So, requiring that a constructor contain a minimum of one parameter reduces the possibility that a constructor will be defined which is expected to be called every time the struct type is built.

 

What is the syntax for calling an overloaded constructor from within a constructor?

You may have noticed that this() and constructor-name() do not compile.

The syntax for calling another constructor is as follows:

class A

{

   A (int i) { }

}

 

class B : A

{

   B() : base (10)    // call base constructor A(10)

      { }

 

   B(int i) : this()  // call B()

      { }

 

   public static void Main() {}

}

 

Are C# parameters passed by reference or by value?

All parameters are passed by value by default in C#. However, know that when passing a reference type, a reference is being passed—by value—rather than an object itself. The Java language works in the same way.

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_Are_CSharp_parameters_passed_by_reference_or_by_value"

Can a property have different get and set access?

Prior to C# version 2.0, no. However, in version 2.0, the restriction was lifted. In later versions, a property can be defined with different access modifiers for its get and set methods.

Can const and static be used together?

No. The C# specification states that the inclusion of the static modifier is redundant and prohibited; because, constant declarations are implicitly static. Allowing both could cause confusion when one declaration includes the modifier but another does not. However, there is no prohibition against specifying an access modifier which is also the default. Perhaps the intention is to permit redundant modifiers when there is a choice but to deny them when there is no choice

Can I directly call a native function exported from a DLL?

Yes. The following example uses the minimum requirements for declaring a C# method implemented in a native DLL. The method Test.MessageBoxT() is declared with static and external modifiers. And, it has the DllImport attribute which notifies the compiler that the implementation comes from the user32.dll under the default name of MessageBoxT.

using System.Runtime.InteropServices;

 

class Test

{

   [DllImport("user32.dll")]

   public static extern int MessageBoxT

      (int h, string m, string c, int type);

 

   public static int Main()

   {

      return MessageBoxT(0, "Hello, World!", "Title", 0);

   }

}

Do unused references to external assemblies lead to code bloat?

The .NET platform promotes the binary reuse of types. It is common practice to set references to external assemblies using Visual Studio .NET's Add Reference menu item. Many developers believe that adding unnecessary and, therefore, unused external references will result in code bloat—binary code loaded into the program even though unused. But, in fact, when assembly references are added or the using keyword is used, csc.exe—the C# compiler—ignores assemblies which are not actually used by the application.

For example, if references to System.Net.dll and System.Reflection.dll were added, but were not otherwise referenced in the application, the compiler would only reference the mandatory mscorlib.dll. Inspect the following sample code:

using System;

using System.Net;          // Ignored by C# compiler.

using System.Reflection;   // Ignored by C# compiler.

 

public class TestClass

{

  public static void Main()

  {

    Console.WriteLine ("No code bloat here!");

  }

}

When a .NET assembly is opened using ildasm.exe, the MANIFEST icon can be double clicked, opening a window describing the binary being examined. A list of external assemblies compiled with the current assembly appears near the top:

.assembly extern mscorlib

{ … }

So, it is a waste of time to strip out unused assembly references and using statements from an application; because, the C# compiler does this automatically. However, many excellent programmers consider it poor form to include unused references in source code.

Does C# have its own class library?

No. The .NET Framework has a comprehensive class library called the .NET Framework Class Library and Base Class Library—most of which is directly available to C# developers. So, C# does not need a private class library separate from the .NET Framework.

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_Does_CSharp_have_its_own_class_library"

Does C# have macros or a preprocessor?

C# does not have macros. And, strictly speaking, C# does not have a preprocessor either. However, C# does have conditional compilation symbols which are used to guide compilation. These symbols can be defined either in compiler parameters or in the source code. The "preprocessing" directives in C# are so-called because of the preprocessors of its ancestors—C and C++. The following driectives are found in the ECMA specification:

Directive

Usage

#define, #undef

Define and undefine conditional compilation symbols.

#if, #elif, #else, #endif

Skip sections of source code conditionally.

#line

Control line numbers emitted with errors and warnings.

#error, #warning

Issue errors and warnings.

#region, #endregion

Mark sections of source code explicitly.

Refer to section 9.5 of the ECMA specification for further information on the pre-processing directives.

Also, the Conditional attribute of a method can be used to effect conditional compilation. Thus, calls to the method will be compiled only if the appropriate symbol is defined. For further information on the Conditional attribute, refer to section 24.4.2 of the ECMA specifcation.

Does C# support custom exceptions?

All that needs to be done to create a custom exception in C# is for the new exception class to subclass System.Exception.

Does C# support jagged arrays?

In both the C and C++ languages, each subarray of a particular multi-dimensional array must have identical dimensions. In other words, arrays must be orthogonal. However, in both the Java and C# languages, arrays need not be orthogonal; because, arrays are constructed as arrays of arrays.

In C#, each array is one-dimensional. Therefore, jagged arrays of varying sizes can be built. The contents of a jagged array is arrays of instances or of references to arrays. Therefore, the rows and columns of a jagged array need not be of uniform length.

The following C# example illustrates how to construct a jagged array—the code works in either the Java or C# language:

int [][]anArray = new int[3][];

anArray [0] = new int[7];

anArray [1] = new int[13];

anArray [2] = new int[5];

Does C# support variable method arguments (vararg)?

Yes. The params keyword can be applied to a method parameter which is an array. Upon method invocation, the array elements can be supplied as a comma (,) separated list.

For example, if the method parameter were an array of object, the source code would be similar to the following:

void paramsExample

   (object argument-1,

    object argument-n,

    params object[] variableArguments)

{

   foreach (object arg in variableArguments)

   {

   }

}

And, this method can be invoked with any number of arguments of any type. Here is a sample invocation:

paramsExample (1, 2.3m, 4.5f, "arbitrary string", new UserDefinedType());

But, many developers would prefer to pass a variable number of arguments of a single, specific type—e.g. string—rather than object.

How call overloaded operators from non-supporting languages?

In C# as in C++, operators can be overloaded to handle custom types. For example, assume a structure named BigPoint which features an overloaded plus (+) operator allowing the "addition" of two BigPoint objects as follows:

// Add two BigPoint types to obtain a 'larger' Point.

 

BigPoint largePoint = pointOne + pointTwo;

Many C# developers avoid this powerful technique for fear of building non-CLS-compliant types. But, there is no reason to fear compatibility. Every overloaded operator maps to a special static CIL method which is invocable by languages without native support for operator manipulation.

In this example, operator + maps to a method named op_Addition(). So, a Visual Basic .NET programmer could interact with BigPoint like this:

' Add two BigPoint types to obtain a 'larger' Point.

 

Dim largePoint as BigPoint = _

   BigPoint.op_Addition (pointOne + pointTwo)

How can I force garbage collection?

You can't. However, you can request garbage collection. If, when, and how it runs is up to the Common Language Runtime (CLR).

To request that the CLR deallocate unreferenced objects, call:

System.GC.Collect();

In addition, to request that finalizers be run on unreferenced objects, call:

System.GC.RunFinalizers();

An unreferenced object is one which has been created, but has no references to it; that is, all references to it are null.

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_How_can_I_force_garbage_collection%3F"

How can I output simple debugging messages?

Although Visual Studio sports many useful debugging features including line-by-line stepping through source code, there are times when outputting simple text strings with variable values for debugging is more efficient.

By using the Write* methods of the System.Diagnostics.Debug class, messages can be output in a way similar to the OutputDebugString function of the Win32 API. But, the charm of the Debug class is that when building an application using the default Visual Studio Release configuration, no source code lines are generated for your Debug.Write* class. Therefore, no performance penalty is incurred by using the Debug class in release code.

To use the Debug class, follow this example:

using System.Diagnostics;
 
Debug.Write ("Debugging string");

In addition to the Write method, WriteIf, WriteLine, and WriteLineIf may be called. Here is a brief example:

bool @flag1 = true;
bool flag2  = false;
Debug.WriteLineIf (@flag1 || flag2, "Conditional debug message!");

When debugging an application with the Visual Studio debugger, all messages emitted by Write method calls show up in the Output window (View / Output menu command or Ctrl+W,O). However, when running an application outside the debugger—e.g., after starting it from Windows Explorer—, the messages can still be viewed using tools such as DebugView of Sysinternals.

Note: If the application is built using the default Release configuration, not even DebugView will display the messages; because, the Debug.Write* calls are completely eliminated. Also, code generation can be controlled by defining the DEBUG conditional directive.

Tip: The .NET debugging and tracing architecture allows redirecting debugging messages to various destinations, e.g. text files.

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_How_can_I_output_simple_debugging_messages"

How check the object type at runtime?

How can the type of an object be checked at runtime? The is keyword is used for this purpose. The following is an example of usage for the is keyword:

using System;

 

class ClassAppl

{

   static bool isInteger (object o)

   {

      if (o is int || o is long)

      {

         return true;

      }

      else

      {

         return false;

      }

   }

 

   public static void Main()

   {

      string aString = "C#";

      long longType = 99;

 

      Console.WriteLine ("{0} is {1} an integer", aString,

         (isInteger (aString) ? "" : "not "));

      Console.WriteLine ("{0} is {1} an integer", longType,

         (isInteger (longType) ? "" : "not "));

   }

}

generates the output:

 

 Example output (program output)

C# is not an integer

99 is an integer

How can type name clashes be resolved?

The C# using keyword can be used to supply hints to the C# compiler regarding the fully qualified names of types residing in a specified source (.cs) file. The using keyword can include an alias which can be used to prevent or resolve name clashes.

Assume the following namespace definitions:

namespace Namespace1
{
   public class SampleClass {}  // same classname as below
}
 
namespace Namespace2
{
   public class SampleClass {}  // same classname as above
}

Next, the application tries to create an instance of the Namespace2.SampleClass from the following application:

using Namespace1;
using Namespace2;
 
public class SampleApplication
{
  public static void Main()
  {
    SampleClass sc = new SampleClass ();    
    // Compiler error:  type name clash: 
    // Namespace1.SampleClass or Namespace2.SampleClass ?
  }
}

The resulting type name clash can be resolved by creating an alias as follows:

using Namespace1;
using SampleClass2 = Namespace2.SampleClass;
 
public class SampleApplication
{
  public static void Main()
  {
    SampleClass2 sc = new SampleClass2();    
    // Creates a new Namespace2.SampleClass. Same as: 
    // Namespace2.SampleClass sc = new Namespace2.SampleClass();
  }
}

The using keyword can also be used to resolve type name conflicts for types with "System" in their fully qualified names.

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_How_can_type_name_clashes_be_resolved"

How do I declare an out variable?

An out parameter is used to return a value in the same variable which was passed in as a parameter to the method. Any changes made to the parameter are reflected in the variable.

public class Test

{

   public static void outMethod (out int param1, out int param2)

   {

      param1 = 1;

      param2 = 2;

   }

 

   public static void Main()

   {

      int out1, out2;    // do not initialize variables

      outMethod (out out1, out out2));

      Console.WriteLine (out1); // outputs "1"

      Console.WriteLine (out2); // outputs "2"

   }

}

Use the out keyword on both the method declaration and invocation.

How do I get DllImport to work?

Reference System.Runtime.InteropServices. Mark all methods with the DllImport attribute as public static extern.

using System;

using System.Runtime.InteropServices;

 

class Example

{

   // Use DllImport to import the Win32 MessageBox function.

 

   [DllImport ("user32.dll", CharSet = CharSet.Auto)]

   public static extern int MessageBox

      (IntPtr hWnd, String text, String caption, uint type);

 

   static void Main()

   {

      // Call the MessageBox function using platform invoke.

      MessageBox (new IntPtr(0), "Hello, World!", "Hello Dialog", 0);   

   }

}

How do I make a C# DLL?

Use the /target:library compiler option.

In Visual Studio,

1.     open the Project File's property page;

2.     open CommonProperties -> General -> Output Type;

3.     change the output type to class library;

4.     build the application to create a .dll file.

Set the path where the .dll file is to be stored by setting Configuration Properties -> Build -> Output Path.

How do I use trace and assert?

Add a conditional attribute to the method as indicated below:

using System.Diagnostics.ConditionalAttribute;
 
class Trace
{
   [conditional("TRACE")]
   public void Trace (string str)
   {
      Console.WriteLine (str);
   }
}
 
class Debug
{
   public static void Main()
   {
      Debug.Trace ("Main reached");
   }
}

In the preceding example, the Debug.Trace() call is made only if the preprocessor symbol TRACE is defined at the call site. Preprocessor symbols can be defined on the command line using the /D switch. Conditional methods must have void return type.

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_How_do_I_use_trace_and_assert%3F"

How get the type name at runtime?

To get the name of a C# type at runtime, use the GetType() method of object class. For instance, the following source code:

using System; 
 
class Example
{
   class ClassAppl 
   {    
      static void ShowTypeInfo (object o) 
      { 
      Console.WriteLine ("type name = {0}, 
         full type name = {1}", o.GetType(), 
         o.GetType().FullName ); 
      }
 
      public static void Main()
      { 
         long longType = 99; 
         Example example= new Example(); 
 
         ShowTypeInfo (example); 
         ShowTypeInfo (longType); 
      }
   }
}

generates the following output:

 

 Example output (program output)

type name = Example, full type name = Example

type name = Int64, full type name = System.Int64

 

 

All types inherit from object; so, all types can access GetType().

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_How_get_the_type_name_at_runtime"

How keep a local variable in scope across a try-catch block?

Here is the problem:

try
{
   Connection conx = new Connection();
   conx.Open();
}
catch
{  // fails because conx is out of scope
   if (conx != null)
   {
      conx.Close();
   }
}

The preceding code will not work; because, if the Open fails, then the conx variable goes out of scope before the catch block is entered.

Fortunately, there is a simple fix—just declare the variable before entering the try block.

Connection conx = null;  // declare outside the try block
try
{
 
   conx = new Connection();
   conx.Open();
 
}
catch
{
   if (conx != null)
   {
      conx.Close();
   }
}

For examples of this type, the Connection class could be wrapped in a class which implements the IDisposable interface. In this way, instead of extending the scope of the local variable, a using statement could be used.

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_How_keep_a_local_variable_in_scope_across_a_try-catch_block"

How make sure C# classes will interoperate with other .NET languages?

Ensure that the C# spplication code conforms to the Common Language Specification (CLS). To help achieve compliance, add the [assembly:CLSCompliant(true)] global attribute to all C# source files. This attribute will cause the C# compiler to throw an error if a non-CLS-compliant feature is used.

Retrieved from "http://en.csharp-online.net/CSharp_FAQ:_How_make_sure_CSharp_classes_will_interoperate_with_other_.NET_languages"

How perform a case insensitive string comparison?

A case-insensitive string comparison can be performed in C# using the String.Compare method. The third parameter is a boolean value used to specify that case should or should not be ignored. For example, the following comparison will return false:

if ("c#" == "C#")

but, the following Compare will return true:

if (System.String.Compare ("c#", "C#", true) == 0)

For greater control over string comparisons, the System.Globalization.CompareInfo.Compare() method may be used as follows:

CultureInfo.CurrentCulture.CompareInfo.Compare

   (

   "c#", "C#",

   CompareOptions.IgnoreCase |

   CompareOptions.IgnoreKanaType |

   CompareOptions.IgnoreWidth

   );

System.Globalization.CompareInfo.Compare() has many options, some of which are quite esoteric.

How process command line arguments?

C# command line arguments can be processed as follows:

using System;

 

class CommandLineExample

{

   public static void Main (string[] args)

   {

      Console.WriteLine ("Command line arguments found: ");

      foreach (string argument in args)

      {

         Console.WriteLine (argument);

      }

   }

}

How specify a C# literal type?

Sometimes, it is necessary to notify the C# compiler that a literal must be treated as a certain number type. This can be accomplished by adding a number type suffix to the end of the literal. For example:

1m;  // System.Decimal 
1f;  // System.Single 
1d;  // System.Double 
1U;  // unsigned int
1ul; // unsigned long 

This is a useful feature when a literal must be matched to a signature or a value is specified in order to defeat an undesired implicit cast of 0.5 to a double. For instance:

Hashtable table = new Hashtable (1000, 0.5);

The preceding line will not compile; because, the Hashtable constructor expects parameters (int, float); but, the preceding is (int, double). To defeat the implicit cast, use a line similar to the following:

Hashtable table = new Hashtable (1000, 0.5f);

A complete listing of the suffixes is specified in the C# Language Specifcation sections specified below.

How subscribe to events exposed by remoted objects?

Beware: Remoting events across machines is fraught with peril. A client which dies or is slow can easily exhaust a server's threadpool.

In order to make a call, delegates need to know the type of the associated method. Within a single application domain, this is a simple matter; since, the server—the object firing events—has access to the client's type information via the delegate.

But, during remoting, the server probably has no information about the client. For events from the server to fire in the client application domain, the client must be derived from MarshalByRefObject. This is necessary; so, that the server will perform a call back to the client versus a copy of the client object which is passed to the server.

An easy, but inelegant, way to achieve this is to place a copy of the client assembly in the same directory where the server directory resides. The problem with this approach is that the client type is exposed unnecessarily.

A better, although more complex, solution is to create a single assembly which is referenced by both the client and the server. This assembly will include a shim class which exposes methods sharing the signature of the events to be shimmed. Also, the assembly provides an interface with methods that share the signature of the events. The shim takes a reference to the interface; and, the methods aggregate the call to the interface that was passed in. The constructor is a great place to pass in the interface implementation.

Lastly, the client object implements the interface. When subscribing to the events exposed by the server, attach the delegates to the methods on the shim, which will be passed a client object's implementation.

For all this to function correctly, the TypeFilterLevel property of the sink provider for the server must be set to TypeFilterLevel.

How to obtain type information on the fly using typeof?

.NET assemblies contain detailed type information describing the structure of every internal and external type. This can be verified by loading an assembly into ildasm.exe and typing Ctrl-m. Many methods in the .NET base class libraries require passing in the type information for a given item. There are several approaches to obtaining type information for a given method invocation.

Firstly, all types inherit the public System.Object.GetType() method. So, the following example will work:

// Get type information from a variable.

 

TestType tt = new TestType();

Type tipe = tt.GetType();

RequiresTypeInfo (tipe);       // Imaginary method requiring type

However, it may seem rather involved and expensive to create a type simply to call the inherited GetType() method. The C# language offers the typeof operator to simplify the process. The typeof operator does not require the creation of the item in question. Instead, just specify the name of the type as an argument as in the following:

// Get type information using the typeof operator.

 

RequiresTypeInfo (typeof (TestType)); // Imaginary method requiring type

How use an alias for a class or namespace?

The using directive can be used to create an alias for a long class name or a namespace. Then, the alias can be used instead—anywhere the class name or namespace could normally appear.

The using alias is scoped within the namespace in which it is declared. The following is an example of a using alias:

// Namespace alias example

using activation = System.Runtime.Remoting.Activation;

 

// Class name alias example

using arrayList = System.Collections.ArrayList;

 

// use the aliases ...

 

arrayList aList = new arrayList();      // creates an ArrayList

 

activation.UrlAttribute urlAttribute;   // is equivalent to ...

// System.Runtime.Remoting.Activation.UrlAttribute urlAttribute;

How would I create a Delegate or MulticastDelegate?

In order to declare a delegate, most programming languages require the programmer to specify both an object reference and a method to invoke. C# requires only a single parameter—the method address—to declare a delegate. C# infers the other pieces of information.

Here is an example:

using System.Threading;

 

ThreadStart: AClass MyClass = new AClass();

 

ThreadStart aDelegate = new ThreadStart (MyClass.aMethod);

Thus, delegates can invoke either instance methods or static class methods using a single syntax.

Is there C# support for C-type macros?

I am afraid not. C# does not have macros.

What are the C# character escape sequences ()?

An escape sequence allows you to enter any Unicode character, even if it is not readily available on a standard keyboard. Escape characters may appear within identifiers, strings, and certain other places. An escape character has the following form:

The C# compiler recognizes the following character escape sequences:

Escape sequence

Interpretation

'

single quote, needed for character literals

"

double quote, needed for string literals

backslash, needed for string literals

 


Today, there have been 7 visitors (10 hits) on this page!
This website was created for free with Own-Free-Website.com. Would you also like to have your own website?
Sign up for free