Naming a variable in C# and Best Practices

C# requires the programmer to use names from letters chosen from a through zA through Z, and numbers are chosen from 0 through 9.

Best practise to for naming a variable is to use :

  1. Camel Case. First word in variable name is in small letter and Second word in variable name is capital letter. Example : rollNumber
  2. Use relevant names to explain the variable use instead of names like x , y and z. Example : candidateName

Algorithms : Given two strings , write a method to decide if one is permutation of other

Algorithms : Given two strings , write a method to decide if one is permutation of other 

// C# program to check whether two strings are permutations of each other
using System;

class AllTechnicalFAQs
{

/* function to check whether two strings are permutation of each other */
public bool isPermutation(String str1, String str2)
{
// Get lenghts of both strings
int n1 = str1.Length;
int n2 = str2.Length;

// If length of both strings is not same,
// then they cannot be Permutation
if (n1 != n2)
return false;
char [] ch1 = str1.ToCharArray();
char [] ch2 = str2.ToCharArray();

// Sort both strings
Array.Sort(ch1);
Array.Sort(ch2);

// Compare sorted strings
for (int i = 0; i < n1; i++)
if (ch1[i] != ch2[i])
return false;

return true;
}

/* Main Block*/
public static void Main(String[] args)
{
String str1 = Console.Readline();
String str2 = Console.Readline();
if (isPermutation(str1, str2))
Console.WriteLine(“Yes”);
else
Console.WriteLine(“No”);
}
}

// This code contributed by Rajput-Ji

Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?

Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?

// C# program to demonstrate
// ToCharArray() method
using System;
class AllTechnicalFAQs {

// Main Method
public static void Main()
{

String str = Console.ReadLine();

// copy the string str to chars
// character array & it will start
// copy from ‘G’ to ‘s’, i.e.
// beginning to ending of string
char[] chars = str.ToCharArray();

bool isFound = false;

// to display the resulted character array
for (int i = 0; i < chars.Length; i++)
        {
                          for (int j = i+1; i < chars.Length; i++)
                          {
                               if ( chars[I] ==chars[j] )
                                   isFound = true
                          }
                }
              if ( isFound == true )
                       Console.Writeline(“Not Unique”);
             else
                      Console.Writeline(“Unique”);
}
}

.NET components call COM components.

 .NET Components can call COM components

The proxy used in calling unmanaged code from managed code is known as a Runtime-Callable Wrapper, or RCW.

Ways to create RCW are listed below :

1. Converting Metadata with TLBIMP

 tlbimp (type library importer) is tool which reads the metadata from a COM type library and creates a matching CLR assembly for calling the COM component.

tlbimp COMsupport.dll /out:NETsupport.dll

2. Using COM Components Directly

1.     Click Project, and then click Add Reference.
2.     In the Add Reference dialog box, click the COM tab.
3.     Select the type library you wish to use from the list and click Select, or use the Browse button to locate a component that’s not listed. The selected components will be added to the lower listview in the dialog box.
4.     Click OK to create RCWs for the selected type libraries in your Visual Basic .NET or C# project.

 

New Features of VB.NET and C# languages in 2005 version

New Features of VB.NET and C# languages in 2005 version

VB.NET C#
Visual Basic 2005 has many new and improved language features — such as inheritance, interfaces, overriding, shared members, and overloading — that make it a powerful object-oriented programming language. As a Visual Basic developer, you can now create multithreaded, scalable applications using explicit multithreading. This language has following new features,

  1. Continue Statement, which immediately skips to the next iteration of a Do, For, or While loop.
  2. IsNot operator, which you can avoid using the Not and Is operators in an awkward order.
  3. 3. Using...End. Using statement block ensures disposal of a system resource when your code leaves the block for any reason.
4.  Public Sub setbigbold( _
5.      ByVal c As Control)
6.  Using nf As New _
7.    System.Drawing.Font("Arial",_
8.    12.0F, FontStyle.Bold)
9.    c.Font = nf
10.  c.Text = "This is" &_
11.  "12-point Arial bold"
12.End Using
End Sub
  1. Explicit Zero Lower Bound on an Array, Visual Basic now permits an array declaration to specify the lower bound (0) of each dimension along with the upper bound.
  2. Unsigned Types, Visual Basic now supports unsigned integer data types (UShort, UInteger, and ULong) as well as the signed type SByte.
  3. Operator Overloading, Visual Basic now allows you to define a standard operator (such as +, &, Not, or Mod) on a class or structure you have defined.
  4. Partial Types, to separate generated code from your authored code into separate source files.
  5. Visual Basic now supports type parameters on generic classes, structures, interfaces, procedures, and delegates. A corresponding type argument specifies at compilation time the data type of one of the elements in the generic type.
  6. Custom Events. You can declare custom events by using the Custom keyword as a modifier for the Event statement. In a custom event, you specify exactly what happens when code adds or removes an event handler to or from the event, or when code raises the event.
  7. Compiler Checking Options, The /nowarn and /warnaserror options provide more control over how warnings are handled. Each one of these compiler options now takes a list of warning IDs as an optional parameter, to specify to which warnings the option applies.
  8. There are eight new command-line compiler options:
    1. The /codepage option specifies which codepage to use when opening source files.
    2. The /doc option generates an XML documentation file based on comments within your code.
    3. The /errorreport option provides a convenient way to report a Visual Basic internal compiler error to Microsoft.
    4. The /filealign option specifies the size of sections in your output file.
    5. The /noconfig option causes the compiler to ignore the Vbc.rsp file.
    6. The /nostdlib option prevents the import of mscorlib.dll, which defines the entire System namespace.
    7. The /platform option specifies the processor to be targeted by the output file, in those situations where it is necessary to explicitly specify it.
    8. The /unify option suppresses warnings resulting from a mismatch between the versions of directly and indirectly referenced assemblies.
With the release of Visual Studio 2005, the C# language has been updated to version 2.0. This language has following new features:

  1. Generics types are added to the language to enable programmers to achieve a high level of code reuse and enhanced performance for collection classes. Generic types can differ only by arity. Parameters can also be forced to be specific types.
  2. Iterators make it easier to dictate how a for each loop will iterate over a collection’s contents.
3.  // Iterator Example
4.  public class NumChar
5.  {
6.  string[] saNum = { 
7.    "One", "Two", "Three", 
8.    "Four", "Five", "Six", 
9.    "Seven", "Eight", "Nine", 
10.  "Zero"};
11.public 
12. System.Collections.IEnumerator 
13. GetEnumerator()
14.{
15.foreach (string num in saNum)
16.yield return num;
17.}
18.}
19.// Create an instance of 
20.// the collection class
21.NumChar oNumChar = new NumChar();
22.// Iterate through it with foreach
23.foreach (string num in oNumChar)
24.Console.WriteLine(num);
  1. Partial type definitions allow a single type, such as a class, to be split into multiple files. The Visual Studio designer uses this feature to separate its generated code from user code.
  2. Nullable types allow a variable to contain a value that is undefined.
  3. Anonymous Method is now possible to pass a block of code as a parameter. Anywhere a delegate is expected, a code block can be used instead: There is no need to define a new method.
28.button1.Click += 
29. delegate { MessageBox.Show( 
 "Click!") };
  1. . The namespace alias qualifier (::) provides more control over accessing namespace members. The global :: alias allows to access the root namespace that may be hidden by an entity in your code.
  2. Static classes are a safe and convenient way of declaring a class containing static methods that cannot be instantiated. In C# v1.2 you would have defined the class constructor as private to prevent the class being instantiated.
  3. 8. There are eight new compiler options:
    1. /langversion option: Can be used to specify compatibility with a specific version of the language.
    2. /platform option: Enables you to target IPF (IA64 or Itanium) and AMD64 architectures.
    3. #pragma warning: Used to disable and enable individual warnings in code.
    4. /linkresource option: Contains additional options.
    5. /errorreport option: Can be used to report internal compiler errors to Microsoft over the Internet.
    6. /keycontainer and /keyfile: Support specifying cryptographic keys.

How to call Constructor from another Constructor with same class in C# ?

Calling Constructor from another Constructor with same class

There are two ways to do the above :
1. Use this keyword to acheive this . Example below :
 public class Employee
{
    public Employee(): this(10)
    {
        // This is the no parameter constructor method.
        // First Constructor
    }
    public Employee(int Age)
    {
        // This is the constructor with one parameter.
        // Second Constructor
    }
}
So first constructor will can second constructior using this keyword
2.
public class Employee
{
    public Employee()
    {
        Employee(10)
        // This is the no parameter constructor method.
        // First Constructor
    }
    public Employee(int Age)
    {
        // This is the constructor with one parameter.
        // Second Constructor
    }
}

What is Construction Overloading in C#

Constructor Overloading
Constructor oveloading enables to have constructors with different sets of parameters.

Example below:

public class Employee
{
    public Employee()
    {
        // This is the no parameter constructor method.
        // First Constructor
    }
    public Employee(int Age)
    {
        // This is the constructor with one parameter i.e. Age.
        // Second Constructor
    }
    public Employee(int Age, string Name)
    {
        // This is the constructor with two parameters i.e. Age and Name.
        // Third Constructor
    }
   
}
Call to the constructor now depends on the way you instantiate the object.

For example:

Employee objEmp = new Employee()
// At this time the code of no parameter 
// constructor (First Constructor)will be executed
Employee objEmp = new Employee(12)
// At this time the code of one parameter 
// constructor(Second Constructor)will be
// executed.
 

Write a C# code to get list of parent ASP.NET controls from Child ASP.NET controls

C# code to get list of parent ASP.NET controls from Child ASP.NET controls

private ArrayList WalkthroughContainers(Control ctl)
    {
        ArrayList retContainers = new ArrayList();
        Control parent = ctl.NamingContainer;
        if (parent != null)
        {
            ArrayList sublist = WalkContainers(parent);
            for (int j = 0; j < sublist.Count; j++) retContainers.Add(sublist[j]);
        }
        retContainers.Add(ctl.GetType().Name);
        return retContainers;
    }