Showing posts with label C# Basics. Show all posts
Showing posts with label C# Basics. Show all posts

Wednesday, January 1, 2014

Operator Overloading in C#

In this article we are going to see the operator overloading , operator overloading is a concept where we can overload the method using the Operator , in which the operation between the interaction objects can be defined based on symbol.Let we see  a sample scenario where we can see the stringoperation is a class which have the MethodName is string, when two objects are interact with summation operator then the
result will be the concat of the MethodName with intermediate , symbol

C#


    class Program
    {
        static void Main(string[] args)
        {
            StringOperation operation1 = new StringOperation() { MethodName="public"};
            StringOperation operation2 = new StringOperation() { MethodName = "private" };
            StringOperation operation3 = operation1 + operation2;
            Console.WriteLine(operation3.ToString());
            Console.Read();
        }
    }

    class StringOperation
    {
        public stringMethodName { set; get; }

        public static StringOperation operator+ (StringOperation operation1, StringOperation operation2)
        {
            return new StringOperation() {MethodName = operation1.MethodName+","+operation2.MethodName };
        }

        public override string ToString()
        {
            return MethodName;
        }
    }




Output:
public,private

From this article you can see how to implement the Operator overloading.

Friday, November 1, 2013

C# - Various Ways to Write in a Text File

In C# we can create a file and write the content in various ways,In this article we will see that how we can create a file in various ways, check the existence of file in computer , delete the file and rename the file

Create a File and Write the Content ;

Way 1 :
In this example we are going to create a File and write the content in each and every line with increment in number up to 10000 lines in a second.

class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i <=10000; i++)
            {
                WriteLog(string.Format(" Value {0} "+Environment.NewLine,i));
            }
            Console.Read();
        }

        static void WriteLog(string message)
        {
            File.AppendAllText(@"D:\sample.txt", message);
        }
    }


 Output:

Way 2:
This example uses the filestream class in which we can change the settings options , and streamwriter class to write the content in file.   writer.Flush(); method is important if this method is not called then file will create but content will not write. if close is mentioned then at finally content will be write in file.

static void Main(string[] args)
        {
            FileStream fs=new FileStream(@"D:\sample.txt",FileMode.Append);
            StreamWriter writer = newStreamWriter(fs);
            writer.WriteLine("Hi this is testing application !/");
            writer.WriteLine("I am Rajesh");
            writer.WriteLine(":)");
            writer.Flush();
            writer.Close();
            fs.Close();
            Console.Read();
        }







Use File.Delete(@"D:\sample.txt") method to delete a file in particular path

To Check whether File is present in the particular path use the File.Exists(@"D:\sample.txt") method.

I Hope from this article you will learn how to create  a text file and write the content in it. as well delete and file exists 




Saturday, September 7, 2013

Abstraction and Encapsulation in C#

What is Encapsulation ?
      Encapsulation is a one of the principle of object oriented programming. The concept of encapsulation is hiding  the Data from the outside world, i.e Hiding the Member, Field, Property from the outside of the class is known as Encapsulation.

     In Real time Example how we can understand that. Let we take Laptop as Example. In Laptop we know how to operate , When pressing the windows key , Start up is launched, But how it is launched is not exposed to the user, here it is encapsulated. Make this process as private from user.

  In C# encapsulation is done by Access Specifier "private" keyword

Example 


    public class Car
    {
        public string Model { set; get; }

        private intEngineSpeed;

        public void Start()
        {
       
        }

        public void Off()
        {
       
        }

        private voidEngineProcess()
        {
            EngineSpeed = 170;
        }
    }

    public class Driver
    {
        public void work()
        {
            /* Car class hides the EngineProcess() member and EngineSpeed field from outside the class (Encapsulation)*/
            Car Honda = new Car();
            Honda.Model = "SDF324";
            Honda.Start();
            Honda.Off();
        }
    }



   In the above example , Car class encapsulates the EngineProcess member from outside the class and also EngineSpeed Field is hides from outside the class.

What is Abstraction ?
     Abstraction is also another importance concepts of Object Oriented Programming. Abstraction is Process of Exposing a necessary information and Data to the outside of class. using the access specifiers.

In C# we have different types of access specifier,
1. private
2. public 
3. protected
4. internal
5. protected internal

What is the usage of access specifier ?

Access specifier is used to specify the what type of access can given for method,class,variable,property, event when it is try to invoke from other class , other class which is present in other project. In C# there is various Access Specifiers
1. Public
2. Private
3. Protected
4. Internal
5. Protected Internal

Here Assembly consider as Project in IDE

public

The type or member can be accessed by any other code in the same assembly or another assembly that references it.

private
The type or member can be accessed only by code in the same class or struct.

protected
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.


Sunday, July 14, 2013

LINQ - Select the required data from collection





























                                                                                                                                                                     
As the Dot Net have more techniques to iterate and fetch the data from collection, One of the best thing is LINQ. Linq is used in Objects, XML, Dataset etc.

Now, we are going to see a Linq sample Which will select the records from Collection of custom template.

In this Example we will create a Employee class with some property [Name,Age,Sex,Country, Phone Number],Based on that class create a employee collection .

    enum Gender
    {
        Male,
        Female
    }

    class Employee
    {
        public string Name { set; get; }

        public string Country { set; get; }

        public Gender Sex { set; get; }

        public int Age { set; get; }

        public int PhoneNo { set; get; }

    }


Select the employees who are male
      




















class Program
    {
        static List GetEmployeeCollection()
        {
            List _emp = new List();
            _emp.Add(new Employee() 
                    { 
                        Name = "Stepen", 
                        Age = 31, 
                        Sex=Gender.Male, 
                        Country = "US", 
                        PhoneNo = 2341094 
                    });

            _emp.Add(new Employee() 
                    { 
                        Name = "Daniel", 
                        Age = 21,
                        Sex=Gender.Male, 
                        Country = "US",
                        PhoneNo  = 4563234 
                    });

            _emp.Add(new Employee() 
                    { 
                        Name = "Suresh", 
                        Age = 22,
                        Sex = Gender.Male, 
                        Country = "INDIA", 
                        PhoneNo = 8574094 
                    });
            _emp.Add(new Employee() 
                    { 
                        Name = "Indhu", 
                        Age = 35, 
                        Sex = Gender.Female, 
                        Country = "INDIA", 
                        PhoneNo = 23417546 
                    });
            _emp.Add(new Employee() 
                    { 
                        Name = "Vinay", 
                        Age = 41, 
                        Sex = Gender.Male, 
                        Country = "UK", 
                        PhoneNo = 23456788 
                    });
            _emp.Add(new Employee() 
                    { 
                        Name = "Sundar", 
                        Age = 21, 
                        Sex = Gender.Male, 
                        Country = "UK", 
                        PhoneNo = 33425673 
                    });
            _emp.Add(new Employee() 
                    { 
                        Name = "Mark", 
                        Age = 36, 
                        Sex = Gender.Male, 
                        Country = "INDIA", 
                        PhoneNo = 88765456 
                    });
            _emp.Add(new Employee() 
                    { 
                        Name = "Alex", 
                        Age = 26, 
                        Sex = Gender.Male, 
                        Country = "US", 
                        PhoneNo = 88764546 
                    });
            _emp.Add(new Employee() 
                    { 
                        Name = "Maria", 
                        Age = 27, 
                        Sex = Gender.Male,
                        Country = "JAPAN", 
                        PhoneNo = 33245433 
                    });
            return _emp;
        }

        static void Main(string[] args)
        {   
            /* print  the employees information who are male  */
            foreach (Employee emp in GetEmployeeCollection().
                                                         Where(x => x.Sex == Gender.Male))
            {
                Console.WriteLine(" Employee Name {0},\tAge {1},\tSex {2},\tcountry {3}", emp.Name, 
                                                          emp.Age, emp.Sex, emp.Country);
            }

            Console.Read();
        }

    }

Output















 Select the employees who are born in "US"

/* print  the employees information who are in Country "US"  */
            foreach (Employee emp in GetEmployeeCollection().Where(x => x.Country == "US"))
            {
                Console.WriteLine(" Employee Name {0},\tAge {1},\tSex {2},\tcountry {3}", 
                                                emp .Name, emp .Age, emp .Sex, emp .Country);

            }

Output :





Select All Emplloyees who are the age above 26 in India

 /* print  the employees who are in Country "India" and age is greater than 26   */
            foreach (Employee emp in GetEmployeeCollection().Where(x => x.Country == "INDIA"  &&                                                                                                                 x.Age > 26 ))
            {
                Console.WriteLine(" Employee Name {0},\tAge {1},\tSex {2},\tcountry {3}", 
                                                emp .Name, emp .Age, emp .Sex, emp .Country);

            }

Output 


Group the employees based on the Country

 /* print  the employees information who are in Country "US"  */
             foreach (var empgrp  in GetEmployeeCollection().GroupBy(x=>x.Country).Select(x=>new                                                                                                                                              {x.Key,x}))
            {
                Console.WriteLine("Country {0}", empgrp.Key);
                foreach(Employee emp in empgrp.x)
                Console.WriteLine(" Employee Name {0},\tAge {1},\tSex {2}", emp.Name, emp.Age,                                                               emp.Sex);
                Console.WriteLine();
            }

            Console.Read();



Output

Country US Employee Name Stepen, Age 31, Sex Male Employee Name Daniel, Age 21, Sex Male Employee Name Alex, Age 26, Sex Male Country INDIA Employee Name Suresh, Age 22, Sex Male Employee Name Indhu, Age 35, Sex Female Employee Name Mark, Age 36, Sex Male Country UK Employee Name Vinay, Age 41, Sex Male Employee Name Sundar, Age 21, Sex Male Country JAPAN Employee Name Maria, Age 27, Sex Male


Saturday, July 13, 2013

Program to Print Password char on Enter Password in Console Application [Masking the Password]

     




  
                                                                                                                                                              Most of the Time developers may face this thing that while receive a password from user through console Application , The password is visible in the window for the user it leads to others knew our password.so this application will tell us that how to get the password in console application as Password char 

Code :



Output for this Program:








Tuesday, July 9, 2013

C# Running Multiple threads at a same time and wait for all of them to Finish

Some times we have a scenario to do the task in multiple threads and execute the threads at a same time. Execute the threads at a same time is easy but wait for all threads to finish and then continue the next process is little bit tedious. This can be done in various ways.

Now we can see some of them Samples how we can make wait for finish the all tasks.

ThreadPool

What is Thread Pool ?
       ThreadPool is basically a collection of Threads ,Which will run the threads in Asynchronous process.This  manages the execution of threads.

Things to be Remember when using ThreadPool 

1. We are giving a method reference to the ThreadPool for execution.
2. The ThreadPool waits for an Ideal thread.
3. When Ideal threads found Thread pool uses it to execute our method.
4. Thread executed and terminated
5. ThreadPool returns the thread and make it availble for other threads to process.


        var items = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
CountdownEvent countdown
= new CountdownEvent(items.Length))

foreach (var item in items)
{
ThreadPool.QueueUserWorkItem(o =>
{
Thread.SpinWait(3000);
Console.WriteLine("Thread Done!");
countdown
.Signal();
});
}
countdown
.Wait();

Console.WriteLine("Job Done!");

async and await (.Net 4.5)

       using async and await you can avoid the performance bottleneck and improve the performance of the Application. Traditional way of call a async program little bit tedious, But in 4.5 we have Async and Await make this option easy for us.The aync and await keyword are the heart of asynchronous programming.

To do the Async Program Following things should be remember ,

1. async modifier should be included in method signature.
2. The name of the async method should end with "Async" suffix
3. Return type must be void,Task, Task no return 
4. On call the Task object after the await makes the thread to wait for finish the Task.
static void Main(string[] args) { Task<string> runItTask = Run(); Console.WriteLine("End of Main"); Console.ReadLine(); } static async Task<string> Run() { Task<string> t = new Task<string> ( () => { Thread.Sleep(5000); Console.WriteLine("Ended the task"); return "Rajesh"; } ); // start the task t.Start(); string result = await t; Console.WriteLine("After await, result = '" + result + "'"); return result; } 
 
 























Output :  
   Ended the task 
   After await, result = Rajesh
   End of Main 


  CountdownEvent    
           CountdownEvent is the class which holds the count integer of threads and make count all the threads signalled, it make program hold to finish all threads on call a method cntevent.Wait();




Output :




Manual Reset Event 

      In the below code we can see the multi threading 10 threads are invoked , ManualResetEvent will make a wait for the program to hold up the signal got received or Set. In the Below code We are signalling the ManualResetEvent at the Last thread had finished there execution.


        resetEvent.WaitOne();
The above code will wait for signaling from the Event to execute the next line.

How it is knew that last Thread is finished the task. Another static class Interlocked.Decrement ,which will  decrement the variable value at the stage of each task has to be finish. Variable value is decrement with the Ref so the Change must be reflected in all threads. Interlocked.Decrement make a lock on variable and  hold the other threads to wait to access the variable to change .

When the variable reaches 0 that indicates that all threads are finished there Task. then we can signal the ManualResetEvent.Set(),

        int num = 10;        
int process = 10
        ManualResetEvent resetEvent = new ManualResetEvent(false);
for (int i = 0; i < num; i++) { new Thread(delegate() { Console.WriteLine(Thread.CurrentThread.ManagedThreadId); if (Interlocked.Decrement(ref process) == 0) resetEvent.Set(); }).Start(); } /* Wait for task to finish */ resetEvent.WaitOne(); Console.WriteLine("Finished.");