Objects in this mirror are closer to Microsoft Technologies. DNM objective is to help users on Microsoft technologies by providing Articles, snippets, Interview Questions.
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

03 September 2012

convert IP address to binary format using IPAddress Class in C#


In this snippet we will see how to convert an IP address to binary format using System.Net.IPAddress class.

static List<string> ConvertIPAddressToBinary(string input)
        {
           IEnumerable<string> binaries= IPAddress.Parse(input).GetAddressBytes().Select( x=> Convert.ToString(Convert.ToInt32(x), 2).PadLeft(8, '0'));
           return binaries.ToList();
        }
 
  static void Main()
        {
            List<string> listBinaries = ConvertIPAddressToBinary(“192.168.0.1”)
            foreach (string binary in listBinaries)
            {
                Console.Write(binary + " ");
            }
        }
Output : 11000000 10101000 00000000 00000001

IPAddress class contains the address of a computer on an IP network and supports IPv4 or IPv6.

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

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.

06 July 2012

Vairables in c# - Different type of variables


In this article we will discuss about variables in c#- variable definition, naming a variable, declaration and initialization of variable, different types of variables with example and finally about default values for data types.

“Variable” is simply storage location of data. Variable will take different values at different time during the execution of program.

Naming a variable:
Variable name can consists of alphabets, digits and underscore. 

Following cases should be taken care of while creating a variable.
  • Should not be a reserved keyword. ( like keyword base). If we try give name with keyword then error as "Identifier is expected. 'base' is a keyword".
  • White space is not allowed between the characters.
  •  Length of name is up to 511 characters.
  • Upper case and lower case are distinct. E.g.: Variable count is different from COUNT.
  • Must not begin with digit.
Some of variable names: count, total_count, incValue,var1,Test_123.

Declaration and Initialization of variable:
[access modifier] [data type] [name] = [value];
Every variable has a type (data types) that determines what value can be stored in the variable.
Examples: 
public string name = "DotNet Mirror";
int val1, val2 = 8;  //declaration and initialization of multiple variable at a time

Different type of variables:
  • Instance variable
  • Static variable
  • Value parameters
  • Reference parameters
  • Output parameters
  • Local variables
  • Array elements
Program
Variable identification
   public class TestClass
    {
        int i;
        static int j;
        public void Sample(string k, ref int l, out int m, int[] n)
        {
            m = 20;
            int var;
        }
    }
i - instance variable
j - static variable
k - value parameter
l - reference parameter
m - output parameter
n - array element
var - local variable
 

Note:if you are using out parameter in a method that should be assigned before control leaves the current method.

Variable default values for data types:
When we declare a variable and did not assign any value then it will takes below default values.
Data type
Default value
All integer types
0
bool
True
String
Null
enum
0
decimal
0.0 m
double
0.0d
float
0.0 f
byte
0
All reference types
null