Objects in this mirror are closer to Microsoft Technologies. DNM objective is to help users on Microsoft technologies by providing Articles, snippets, Interview Questions.

31 July 2012

Reverse string using Array.Reverse function in .NET


In this snippet we will a simple program to reverse a string using Array.Reverse function in .NET.
Array.Reverse Method - Reverses the order of the elements in a one-dimensional Array or in a portion of the Array.

Reverse string using Array.Reverse function
   class ReverseString
    {
        static void Main()
        {
            Console.WriteLine(ReverseStr("DotNetMirror"));
            Console.WriteLine(ReverseStr(".NET Mirror"));      
            Console.ReadLine();
        }
        public static string ReverseStr(string s)
        {
            char[] arr = s.ToCharArray();
            Array.Reverse(arr);
            return new string(arr);           
        }

    }

Output:
rorriMteNtoD
rorriM TEN.

Program to find number of occurrences of a character/letter in a sentence in .NET


In this snippet we will see the program to find number of occurrences of a character in a sentence.

   class NoOfTimesLetterAppearedInSentence
    {
        public static void Main()
        {
            char letterToFind = 'r';
            string sentence = "dotnetmirror reflects your knowledge";
            int count = GetLetterCountInSentence(letterToFind, sentence);
            Console.WriteLine("letter {0} found {1} Times in '{2}'",letterToFind,count, sentence);
            Console.ReadLine();
        }
        public static int GetLetterCountInSentence(char letter, string sentence2check)
        {
            int noOfTimes=0;
            for (int i = 0; i < sentence2check.Length; i++)
            {
                if (sentence2check[i] == letter)//if found, increase the count
                {
                    noOfTimes += 1; 
                }
            }
            return noOfTimes; //returns the count of noOfTimes
        }
    }

Output:
letter r found 5 Times in ' dotnetmirror reflects your knowledge'


27 July 2012

Is method overloading supported with different return type with same signature in .NET


No, method overloading does not support with different return type in C#/VB.NET. If the signature is same (data type and order of arguments) and return type is different we will get error in C# or VB.In C# dev,we will get the error after building the project but in case VB.NET we will get the error beforing building the project.
Below is the piece of code to understand easily.
     public int add(int a,int b)
        {
            return a+b;
        }

        public string add(int a, int b)
        {
            return (a + b).ToString();
        }

C# Complile Error as “ ‘Class_Name' already defines a member called 'add' with the same parameter types”
Function add(ByRef a As Integer, ByVal b As Integer) As Integer
        Return a + b
    End Function
    Function add(ByRef a As Integer, ByVal b As Integer) As Integer
        Return a + b
    End Function
VB.NET Complile  error as 'Public Function add(ByRef a As Integer, b As Integer) As Integer' and 'Public Function add(ByRef a As Integer, b As Integer) As String' cannot overload each other because they differ only by return types.

Method overloading can have same method name with different data type and order of the arguments. It will not support different return type for same signature.

25 July 2012

swapping three variables without using temp/fourth variable in C#.NET

In some of interviews, interviewers will ask write a program to swap three numbers without using a fourth variable or temporary (temp) variable. So in this snippet we will see how to swap three numbers without using fourth/temp variable.

Program : Swapping 3 numbers Without temp variable
class SwapThreeNumbersWithoutUsingFourthVariable
{
public static void Main()
{
Console.WriteLine("/****** Program to swap 3 numbers without using temporary variable *******/");
int a = 10, b = 20,c=30;
Console.WriteLine(" Values before swapping a={0} , b={1} , c={2}", a, b,c);
a = a + b + c;
b = a - (b + c);
c = a - (b + c);
a = a - (b + c);
Console.WriteLine(" Values after swapping a={0} , b={1}, c={2}", a, b,c);
Console.ReadKey();
}
}

Output:
Values before swapping a=10 , b=20 , c=30
Values after swapping a=30 , b=10, c=20

windows service is not listing in attach to process window in Visual studio

You have registered your windows service in the services.msc and its running successfully. When the service is running it shows in the task manager.

Err:
If you want debug the window service code, few times it will not show in available process under attach to process window from debugger.
The root cause could be your service is running under local service or system account not by your user account. In Attach to process window, by default the available process will show the processes which are running under your account name.
So in order to resolve the issue please do the following step.
Sol:
Make sure that you are running the visual studio as an administrator and from the attach process window (Debug à Attach to Process) select the checkbox ‘show process from all users’ in the available process section.
Note: If you have small piece of code in Onstart method. By the time you have attached the service the code execution might complete so try to add code Thread.Sleep(3000).

In which session mode session_end event is supported in ASP.NET


Q .In which session mode “session_end” event is supported?


1.       Inproc

2.       Sql server

3.       State server

4.       All the above

Ans : InProc

Explanantion: Session_End event occurs only in 'Inproc' mode. where as State Server and SQL SERVER mode does not have Session_End event.

24 July 2012

NET Program to check whether the given string is palindrome string or not with out using any builtin funcitons


In this snippet we will write a program to check whether the given string is palindrome string or not.

What is palindrome String?
Palindrome string is a string that remains the same when its chars are reversed
Example: string 'wowow' is a palindrome string.
string 'dotnetmirror'- it not a palindrome string.

Snippet:
class PalindromeString
    {
        static bool CheckPalindrome(string CheckString)
        {
            if (CheckString == null || CheckString.Length == 0)
            {
                return false;
            }
            int strMaxIndex = CheckString.Length - 1;
            for (int i = 0; i < CheckString.Length / 2; i++)
            {
                if (CheckString[i] != CheckString[strMaxIndex - i])
                {
                    return false;
                }
            }
            return true;
        }
        public static void Main()
        {
            Console.WriteLine("********** Palindrome string Check Example ********");
            Console.WriteLine();
            Console.Write("Enter string to you want to check: ");
            string str = Console.ReadLine();
            if (CheckPalindrome(str))
            {
                Console.WriteLine("{0} is a Palindrome String", str);
            }
            else
            {
                Console.WriteLine("{0} is not a Palindrome String", str);
            }
           
            Console.ReadLine();
        }
}

Output:
 Example : Input =wowow (palindrome string)
Fig1 : Palindrome string "wowow"








Example : Input =dotnetmirror (not a palindrome string)
Fig2 : Not a Palindrome string "dotnetmirror"

 Example : Input =maddam(palindrome string)
Fig3 : Palindrome string "maddam"
 




18 July 2012

swapping two variables without using temp/third variable and using temp/third variable in C#.NET


 In many of interviews, interviewers will ask write a program to swap two numbers without using a third variable or temporary (temp) variable. So in this snippet we will see how to swap two numbers with/without using third variable.

Program : Swapping 2 numbers With temp variable
class SwapTwoNumbersUsingTempVariable
    {
        public static void Main()
        {
            Console.WriteLine("/****** Program to swap 2 numbers using temporary variable *******/");
            int a = 10, b = 20;
            Console.WriteLine(" Values before swapping a={0} , b={1}", a, b);           
            int tempVar = 0; //temporary variable

            tempVar = a;
            a = b;
            b = tempVar;

            Console.WriteLine(" Values after swapping a={0} , b={1}", a, b);
            Console.ReadKey();
        }
    }

Output:

Swap 2 numbers using temp/third variable
 


Program : Swapping 2 numbers Without temp variable
class SwapTwoNumbersWithoutUsingThirdVariable
    {
        public static void Main()
        {
            Console.WriteLine("/****** Program to swap 2 numbers without using temporary variable *******/");
            int a = 10, b = 20;
            Console.WriteLine(" Values before swapping a={0} , b={1}", a, b);

            a = a + b;
            b = a - b;
            a = a - b;

            Console.WriteLine(" Values after swapping a={0} , b={1}", a, b);
            Console.ReadKey();
        }
    }

Output:
Swap 2 numbers without using temp/third variable

Reverse string without using any built in function in C#.NET


In many of interviews, interviewers will ask write a program to reverse a string without using any built function. So in this snippet we will see how to reverse a string easily without using any built function or string function.



class StringReverseProgram
      {
          static void Main(string[] args)
          {
              string normalStr = "This is DotNetMirror";
              string reverseStr = string.Empty;
              foreach (char chr in normalStr)
              {
                  reverseStr = chr + reverseStr;
              }
              Console.WriteLine(reverseStr); //Output : rorriMteNtoD si sihT
              Console.ReadKey();
          }
    }

Output:
 rorriMteNtoD si sihT


14 July 2012

sample string orderby program in .net using Orderby and OrderByDescending


We will see a sample code to generate a string order by(ascending and descending) with inbuilt string Orderby and OrderByDescending.

Eg : input is "dotnetmirror" and we need generate a output like ''deimnoorrrtt" and "ttrrroonmied"

Program
    class OrderString
    {
        static void Main()
        {
            string str = "dotnetmirror";

            foreach( char c in str.OrderBy(x =>x))
            {
                Console.Write(c);
            }
            foreach (char c in str.OrderByDescending(x => x))
            {
                Console.Write(c);
            }
            Console.ReadLine();
        }
    }

Output:
deimnoorrrtt //ascending order of the string "dotnetmirror"
ttrrroonmied //descedning order of the string "dotnetmirror"

07 July 2012

Method overloading in C#

In this article we will discuss about method overloading concept with examples.

Definition: Method overloading is a concept of using same method name with differing in the number type and order of arguments.

 Example: if we want to add two integers or two float values we can write methods like
Before method overloading
After method overloading
public int AddIntValues(int a1, int a2)
            {
                return a1 + a2;
            }
public float AddFloatValues(float a1, float a2)
            {
                return a1 + a2;
            }
public int Add(int a1, int a2)
            {
                return a1 + a2;
            }
            public float Add(float a1, float a2)
            {
                return a1 + a2;
            }

The compiler will identify which method to execute based on number of arguments and their data types during compilation. 

Below is the example which shows method overloading.

Example:
class Base
    {
        public int Add(int a1, int a2)
        {
            return a1 + a2;
        }
        public float Add(int a1, float a2)
        {
            return a1 + a2;
        }
    }
    class Derived : Base
    {
        public int Add(int a1, int a2, int a3)
        {
            return a1 + a2 + a3;
        }
        public float Add(float a1, int a2)
        {
            return a1 + a2;
        }
    }
 
    class MethodOverloadingUsage
    {
        static void Main()
        {
            Derived obj = new Derived();
            Console.WriteLine(obj.Add(10, 20));
            Console.WriteLine(obj.Add(10, 12.5f));
            Console.WriteLine(obj.Add(10, 20, 30));
            Console.WriteLine(obj.Add(13.5f,10));
            Console.Read();
        }
    }
Output:
30
22.5
60
23.5

When to use: If a method is performing similar action but using different parameters then we can use method overloading.

Data points:
  • Return type of method will not considered for overloading usage
  • Same method name provides different forms so it is example of polymorphism.
  • In method overloading the method name should be same. Parameters (data type and order) and return type can be different for each method which is overloaded.