Showing posts with label C# programing For console Application. Show all posts
Showing posts with label C# programing For console Application. Show all posts

Monday, March 10, 2014

Using Delegates in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace UsingDelegates
{
    public delegate int NumberFunction (int x);

    class Program
    {
        static void Main(string[] args)
        {
            NumberFunction f = Square;
            Console.WriteLine("result of the delegate is {0}", f(5));

            // now change the delgate
            f = Cube;
            Console.WriteLine("result of the delegate is {0}", f(5));

            Console.ReadLine();
        }

        static int Square(int num)
        {
            return num * num;
        }

        static int Cube(int num)
        {
            return num * num * num;
        }
    }
}

Namespaces and Optional Params iN C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NamedOptionalParams
{
    class Program
    {
        static void Main(string[] args)
        {
            // call the Named parameters example
            myNamedParamExample(stateName: "Washington", zipCode: 98121, cityName: "Seattle");
            myNamedParamExample(cityName: "San Francisco", zipCode: 94109, stateName: "California");
            myNamedParamExample(zipCode: 94109, cityName: "New York", stateName: "New York");

            // call the Optional parameters example
            myOptionalParamFunc(15);
            myOptionalParamFunc(10, 2.71828d);
            myOptionalParamFunc(10, 2.71828d, "a different string");
            // myOptionalParamFunc(10, "a different string");

            // Now do both
            myOptionalParamFunc(10, param3: "named and optional in same call!");

            Console.ReadLine();
        }

        static void myOptionalParamFunc(int param1, double param2 = 3.14159d, string param3 = "placeholder string")
        {
            Console.WriteLine("Called with: \n\tparam1 {0}, \n\tparam2 {1}, \n\tparam3 {2}",param1, param2, param3);
        }

        static void myNamedParamExample(string cityName, string stateName, int zipCode)
        {
            Console.WriteLine("Arguments passed: \n\tcityName is {0}, \n\tstateName is {1}, \n\tzipCode is {2}",
                        cityName, stateName, zipCode);
        }
    }
}

Functions Param Modifiers in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FuncParamModifiers
{
    class Program
    {
        static void SquareAndRoot(double num, out double sq, out double sqrt)
        {
            sq = num * num;
            sqrt = Math.Sqrt(num);
        }

        static void Main(string[] args)
        {
            double n = 9.0;
            double theSquare, theRoot;

            SquareAndRoot(n, out theSquare, out theRoot);
            Console.WriteLine("The square of {0} is {1} and its square root is {2}", n, theSquare, theRoot);
           
            Console.ReadLine();
        }
    }
}

ReadingWritingData

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ReadingWritingData
{
    class Program
    {
        static void Main(string[] args)
        {
            // create a path to the My Documents folder and the file name
            string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
                                Path.DirectorySeparatorChar + "examplefile.txt";

            // if the file doesn't exist, create it by using WriteAllText
            if (!File.Exists(filePath))
            {
                string content = "This is a text file." + Environment.NewLine;
                Console.WriteLine("Creating the file...");
                File.WriteAllText(filePath, content);
            }

            // Use the AppendAllText method to add text to the content
            string addedText = "Text added to the file" + Environment.NewLine;
            Console.WriteLine("Adding content to the file...");
            File.AppendAllText(filePath, addedText);
            Console.WriteLine();

            // Read the contents of the file
            Console.WriteLine("The current contents of the file are:");
            Console.WriteLine("-------------------------------------");

            // Read the contents of the file using ReadAllText
            string currentContent = File.ReadAllText(filePath);
            Console.Write(currentContent);
            Console.WriteLine();

            // Read the contents of the file using ReadAllLines
            /*
            string[] contents = File.ReadAllLines(filePath);
            foreach (string s in contents)
            {
                Console.WriteLine(s);
            }
            Console.WriteLine();
            */

            Console.ReadLine();
        }
    }
}

PathOperations

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; // need this for file and directory information

namespace PathOperations
{
    class Program
    {
        static void Main(string[] args)
        {
            // get the path to the documents folder from the Environment class
            string thePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            thePath += @"\testfile.txt";

            // Exercise the Path class methods
            Console.WriteLine("The directory name is {0}", Path.GetDirectoryName(thePath));
            Console.WriteLine("The file name is {0}", Path.GetFileName(thePath));
            Console.WriteLine("File name without extension is {0}", Path.GetFileNameWithoutExtension(thePath));
            Console.WriteLine("Random file name for path is {0}", Path.GetRandomFileName());
        }
    }
}

namespace ExistingDir

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; // need this namespace to work with files and directories

namespace ExistingDir
{
    class Program
    {
        static void Main(string[] args)
        {
            string thePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            // Check to see if a directory exists
            bool dirExists = Directory.Exists(thePath);
            if (dirExists)
                Console.WriteLine("The directory exists.");
            else
                Console.WriteLine("The directory does not exist.");
            Console.WriteLine();

            // Write out the names of the files in the directory
            string[] files = Directory.GetFiles(thePath);
            foreach (string s in files)
            {
                Console.WriteLine("Found file: " + s);
            }
            Console.WriteLine();

            // Get information about each fixed disk drive
            Console.WriteLine("Drive Information:");
            foreach (DriveInfo d in DriveInfo.GetDrives())
            {
                if (d.DriveType == DriveType.Fixed)
                {
                    Console.WriteLine("Drive Name: {0}", d.Name);
                    Console.WriteLine("Free Space: {0}", d.TotalFreeSpace);
                    Console.WriteLine("Drive Type: {0}", d.DriveType);
                    Console.WriteLine();
                }
            }

            Console.ReadLine();
        }
    }
}

namespace Existing

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; // we need to add this reference to use Files and Directory information

namespace Existing
{
    class Program
    {
        static void Main(string[] args)
        {
            bool fileExists = false;
            string thePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string theFile = thePath + @"\testfile.txt";

            fileExists = File.Exists(theFile);

            if (fileExists)
            {
                Console.WriteLine("The file exists");
            }
            else
            {
                Console.WriteLine("The file does not exist, creating it");
                File.Create(theFile);
            }

            if (fileExists)
            {
                Console.WriteLine("It was created on {0}", File.GetCreationTime(theFile));
                Console.WriteLine("It was last accessed on {0}", File.GetLastAccessTime(theFile));

                Console.WriteLine("Moving the file...");
                File.Move(theFile, thePath + @"\newfile.txt");
            }

            Console.ReadLine();
        }
    }
}

Wednesday, February 12, 2014

Using Exceptions In C#

RethrowingExceptions in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RethrowingExceptions
{
    class Program
    {
        static void DoSomeMath()
        {
            int x = 10, y = 0;
            int result;

            try
            {
                result = x / y;
                Console.WriteLine("Result is {0}", result);
            }
            catch
            {
                Console.WriteLine("Error in DoSomeMath()");
                throw new ArithmeticException();
            }
        }

        static void Main(string[] args)
        {
            try
            {
                DoSomeMath();
            }
            catch (ArithmeticException e)
            {
                Console.WriteLine("Hmm, there was an error in there, be careful!");
            }

            Console.ReadLine();
        }
    }
}

Exception Objects In C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionObject
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 10;
            int y = 0;
            int result;

            try
            {
                result = x / y;
                Console.WriteLine("The result is: {0}", result);
            }
            catch (System.DivideByZeroException e)
            {
                Console.WriteLine("Whoops! You tried to divide by zero!");
                Console.WriteLine(e.Message);
            }
            finally
            {
                Console.WriteLine("Just proving that this code always runs.");
            }

            Console.ReadLine();
        }
    }
}

Custome Exceptions iN C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CustomExceptions
{
    public class NoJoesException : Exception
    {
        public NoJoesException() : base("We don't allow no Joes in here!")
        {
            this.HelpLink = "http://www.joemarini.com/";
        }
    }

    class Program
    {
        static string GetName()
        {
            string s = Console.ReadLine();
            if (s.Equals("Joe"))
                throw new NoJoesException();

            return s;
        }

        static void Main(string[] args)
        {
            string theName;

            try
            {
                theName = GetName();
                Console.WriteLine("Hello {0}", theName);
            }
            catch (NoJoesException nje)
            {
                Console.WriteLine(nje.Message);
                Console.WriteLine("For help, visit: {0}", nje.HelpLink);
            }
            finally
            {
                Console.WriteLine("Have a nice day!");
            }

            Console.ReadLine();
        }
    }
}

Using Struct inC#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UsingStructs
{
    public struct Point
    {
        private int xCoord;
        private int yCoord;

        public Point(int x, int y)
        {
            xCoord = x;
            yCoord = y;
        }

        public int x
        {
            get { return xCoord; }
            set { xCoord = value; }
        }

        public int y
        {
            get { return xCoord; }
            set { xCoord = value; }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

Using Interfaces In C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UsingInterfaces
{
    interface ITalkative
    {
        void SayHello();
        void SayGoodBye();
    }

    class myExampleClass : ITalkative
    {
        public myExampleClass()
        {
        }

        public void SayHello()
        {
            Console.WriteLine("Saying hello!");
        }

        public void SayGoodBye()
        {
            Console.WriteLine("Saying goodbye!");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            myExampleClass myEC = new myExampleClass();

            myEC.SayHello();
            myEC.SayGoodBye();

            Console.ReadLine();
        }
    }
}

Sealed Classes Representation In C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SealedClasses
{
    class myExampleClass
    {
        public static string myMethod(int arg1)
        {
            return String.Format("You sent me the number {0}", arg1);
        }
    }

    class mySubClass : myExampleClass
    {
    }

    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

Method Overriding In C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MethodOverriding
{
    class baseClass
    {
        public virtual void doSomething()
        {
            Console.WriteLine("This is the baseClass saying hi!");
        }
    }

    class subClass : baseClass
    {
        public override void doSomething()
        {
            base.doSomething();
            Console.WriteLine("This is the subClass saying hi!");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            baseClass obj1 = new subClass();

            obj1.doSomething();

            Console.ReadLine();
        }
    }
}

Method Overloading In C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MethodOverloading
{
    class Wine
    {
        public int Year;
        public string Name;
        public decimal price;

        public Wine(string s)
        {
            Name = s;
        }
        public Wine(string s, int y)
        {
            Name = s;
            Year = y;
        }
        public Wine(string s, decimal p, int y)
        {
            Name = s;
            price = p;
            Year = y;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Wine w1 = new Wine("Charles Shaw Merlot");
            Wine w2 = new Wine("Mark Ryan Dissident", 2004);
            Wine w3 = new Wine("Dom Perignon", 120.00m, 1994);

            Console.WriteLine("{0}", w1.Name);
            Console.WriteLine("{0} {1}", w2.Year, w2.Name);
            Console.WriteLine("{0} {1} {2}", w3.Year, w3.Name, w3.price);

            Console.ReadLine();
        }
    }
}

Abstract classes in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AbstractClasses
{
    abstract class myBaseClass
    {
       public abstract int myMethod(int arg1, int arg2);
    }

    class myDerivedClass : myBaseClass
    {
        public override int myMethod(int arg1, int arg2)
        {
            return arg1 + arg2;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

Tuesday, February 4, 2014

Ques in C#

using System;
using System.Collections; // we need to add this reference to use Files and Directory information
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Queues
{
    class Program
    {
        static void Main(string[] args)
        {
            Queue myQ = new Queue();

            myQ.Enqueue("item 1");
            myQ.Enqueue("item 2");
            myQ.Enqueue("item 3");
            myQ.Enqueue("item 4");

            Console.WriteLine("There are {0} items in the Queue", myQ.Count);

            while (myQ.Count > 0)
            {
                string str = (string)myQ.Dequeue();
                Console.WriteLine("Dequeueing object {0}", str);
            }

            Console.ReadLine();
        }
    }
}

Array List In C#

using System;
using System.Collections; // we need to add this reference to use Files and Directory information
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArrayLists
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList myAL = new ArrayList();
            myAL.Add("one");
            myAL.Add(2);
            myAL.Add("three");
            myAL.Add(4);
            myAL.Insert(0, 1.25f);

            foreach (object o in myAL)
            {
                if (o is int)
                    Console.WriteLine("{0}", o);
            }
            Console.ReadLine();
        }
    }
}

Value And Reference Types in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ValAndRefTypes
{
    public class Point
    {
        public int x;
        public int y;
    }

    class Program
    {
        static void testFunc1(int arg1)
        {
            arg1 += 10;
            Console.WriteLine("arg1 is {0}", arg1);
        }

        static void testFunc2(Point pt)
        {
            Console.WriteLine("pt.x is {0}", pt.x);
            pt.x += 10;
            Console.WriteLine("pt.x is {0}", pt.x);
        }

        static void Main(string[] args)
        {
            var i = 10;

            testFunc1(i);
            Console.WriteLine("i is {0}", i);
            Console.WriteLine();

            Point p = new Point();
            p.x = 10;
            p.y = 10;
            Console.WriteLine("p.x is {0}", p.x);
            testFunc2(p);
            Console.WriteLine("p.x is {0}", p.x);

            Console.ReadLine();
        }
    }
}