Monday, March 9, 2015

interface c#

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

namespace inter
{

    public interface operations
    {

        void operation();
        int add();
        int sub();
        //int mult();
    }
    public class math : operations
    {
        private int x1;
        private int y1;

     
        public math(int x, int y)
        {
            x1 = x;
            y1 = y;

        }
        public int add()
        {
            return x1 + y1;
        }
        public int sub()
        {
            return x1 - y1;
        }
        public void operation()
        {
            Console.WriteLine("x1: {0}", x1);
            Console.WriteLine("y1:{0}", y1);
            Console.WriteLine("add:{0}", add());
            Console.WriteLine("sub:{0}", sub());
        }
    }
        public class math2 : operations
        {
            private int a;
            private int b;

            public math2(int c, int d)
            {
                a = c;
                b = d;
            }
            public int mult()
            {
                return a * b;
            }
            public void operation()
            {
                Console.WriteLine("a: {0}", a);
                Console.WriteLine("b:{0}", b);
                Console.WriteLine("add:{0}", mult());
               
            }
        }
   
    class Tester
    {
        static void Main(string[] args)
        {
            math madd = new math(20, 30);
            math2 m2= new math2(10,30);
            madd.operation();
            m2.operation();
            Console.ReadKey();
        }
    }
}



operator over loading

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

namespace oprovr
{
    class program
    {
     
       
       
            public int fun(int a, int b)
            {
               
                return(a+b);
            }
            public int fun(int a, int b, int c)
            {
                return(a+b+c);
            }
            public string fun(string a, string b)
            {
                return(a+b);
            }
   
        static void Main(string[] args)
        {
            //Console.WriteLine("enter values");
           //int a=Convert.ToInt32(Console.ReadLine());
           //int b=Convert.ToInt32(Console.ReadLine());
           program f= new program();
            int c=f.fun(3,5);
            int b=f.fun(1,2,3);
            string s = f.fun("over", "loading");
            Console.WriteLine("two sum" +c);
            Console.WriteLine("three sum" +b);
            Console.WriteLine(s);


            Console.ReadKey();
        }
       

    }
}

polyndrom using for loop c#

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

namespace polyn
{
    class Program
    {
        static void Main(string[] args)
        {
            string s,revs="";
            Console.WriteLine("enter string");
            s = Console.ReadLine();
            for (int i = s.Length-1 ; i>= 0; i--)
            {
                revs += s[i].ToString();
            }


            if (revs == s)
            {
                Console.WriteLine("given string is polyndrum \ngiven string is {0}\nrevs string is {1}", s, revs);
            }
            else
            {
                Console.WriteLine("given string is not polyndrum \ngiven string is {0}\nrevs string is {1}", s, revs);
            }
            Console.ReadKey();

        }
    }
}

polyndrom using while c#

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

namespace polyn_while
{
    class Program
    {
        static void Main(string[] args)
        {
            int num, rev = 0, rem,temp=0;
            Console.WriteLine("enter a no");
            num = Convert.ToInt32(Console.ReadLine());
            temp = num;
            while (num > 0)
            {
                rem = num % 10;
                rev= rev * 10 + rem;
                num = num / 10;
            }
            if (rev== temp)
            {
                Console.WriteLine("given no is polyn:{0}",rev);
            }
            else
            {
                Console.WriteLine("given no is not a polyn:{0}", rev);

            }
            Console.ReadKey();
        }
    }
}

prime number c#

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

namespace prime
{
    class Program
    {
        static void Main(string[] args)
        {
                 bool isPrime = true;
            Console.WriteLine("Prime Numbers : ");
            for (int i = 2; i <= 10; i++)
            {
                for (int j = 2; j <= 10; j++)
                {

                    if (i != j && i % j == 0)
                    {
                        isPrime = false;
                        break;
                    }

                }
                if (isPrime)
                {
                    Console.Write("\t" +i);
                }
                isPrime = true;
            }
            Console.ReadKey();
        }
    }
}
        

reverse sentence c#

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

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

        {

         
    string str = Console.ReadLine();
            string strrev = "";
           
            foreach (var word in str.Split(' ') )
            {
                string temp = "";
                foreach (var ch in word.ToCharArray())
                {
                    temp = ch + temp;
                }
                strrev = strrev + temp + " ";
            }
            Console.WriteLine(strrev);
            Console.ReadLine();
        }
    }
}

reverse string

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

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

            string str, revstr = "";
            int length;
            Console.WriteLine("enter string");
            str = Console.ReadLine();
                length= str.Length-1;
            while(length>=0)
            {
                revstr = revstr + str[length];
                length--;
            }
                Console.WriteLine("rev string is {0}", revstr);
                Console.ReadKey();
        }
    }
}

c# string functions

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

namespace stringfun
{
    class Program
    {
        static void Main(string[] args)
        {
                string firstname;
            string lastname;
         
         
            firstname = "nanda kishore";
            lastname = "kishore";


  Console.WriteLine(firstname.Clone());
// Make String Clone
            Console.WriteLine(firstname.CompareTo(lastname));
//Compare two string value and returns 0 for true and
//1 for false;

 Console.WriteLine(firstname.Contains("da")); //Check whether specified value exists or not in string

  Console.WriteLine(firstname.EndsWith("a")); //Check whether specified value is the last character of string
            Console.WriteLine(firstname.Equals(lastname));
//Compare two string and returns true and false


  Console.WriteLine("hash codse",firstname.GetHashCode());
//Returns HashCode of String

  Console.WriteLine("type of stiring",
      firstname.GetType());
//Returns type of string

  Console.WriteLine(firstname.GetTypeCode());
//Returns type of string

  Console.WriteLine(firstname.IndexOf("e")); /*Returns the first index position of specified value
the first index position of specified value*/

  Console.WriteLine(firstname.ToLower());
//Covert string into lower case

  Console.WriteLine(firstname.ToUpper());
//Convert string into Upper case

  Console.WriteLine(firstname.Insert(0, "Hello")); //Insert substring into string

  Console.WriteLine(firstname.IsNormalized());
/*Check Whether string is in Unicode normalization
from C*/


   Console.WriteLine(firstname.LastIndexOf("e")); //Returns the last index position of specified value

 Console.WriteLine(firstname.Length);
//Returns the Length of String

 Console.WriteLine(firstname.Remove(5));
//Deletes all the characters from begining to specified index.

 Console.WriteLine(firstname.Replace('e','i')); // Replace the character

  string[] split = firstname.Split(new char[] { 'i' }); //Split the string based on specified value


            Console.WriteLine(split[0]);
            Console.WriteLine(split[1]);
          //  Console.WriteLine(split[2]);

  Console.WriteLine(firstname.StartsWith("S")); //Check wheter first character of string is same as specified value

  Console.WriteLine(firstname.Substring(2,5));
//Returns substring

  Console.WriteLine(firstname.ToCharArray());
//Converts an string into char array.

  Console.WriteLine(firstname.Trim());
/*It removes starting and ending white spaces from
string.*/
  Console.ReadKey();
         
        }
    }
}
     
 

word count c#

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

namespace word_count
{
    class Program
    {
        static void Main(string[] args)
        {
           
            string str= Console.ReadLine();
              int last = str.Length-1;

  int count = 0;
  for (int i = 0; i <= last; i++)
  {
      if (char.IsLetterOrDigit(str[i]) &&
           ((i <= last) || char.IsWhiteSpace(str[i + 1]) || char.IsPunctuation(str[i + 1])))
      {
          count++;
      }
  }
  Console.WriteLine(count);
  Console.ReadLine();
       
           
        }
    }
}

multi level inheritence using interface

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

namespace inter
{

     interface operations
    {
     
        void operation();
        int add();
         int sub();
       
    }
    public class math1: operations
    {
        public int x=10;
        public int y=20;
      public int add()
        {
            return x + y;
        }
      public int sub()
      {
          return x - y;
      }
       
        public void operation()
        {
            Console.WriteLine("x1: {0}", x);
            Console.WriteLine("y1:{0}", y);
            Console.WriteLine("base add:{0}", add());
           
        }
    }
    public class math2: math1,operations
    {
        public int add()
        {
            return x + y;
        }
       
      public int sub()
        {
            return x*y;
        }
      public void operation()
      {
          Console.WriteLine("\nmath 2 sub :{0}", sub());
          Console.WriteLine("\n math2 add :{0}",add());
      }
     
    }

    public class math3 : math1, operations
    {

        //public int a=10;
        //public int b=50;
       
        public int add()
        {
            return x+y;
        }
        public int sub()
        {
            return x-y;
        }
        public void operation()
        {
            Console.WriteLine("a: {0}", x);
            Console.WriteLine("b:{0}", y);
            Console.WriteLine("\nmath3 add:{0}", add());
            Console.WriteLine("math3 sub:{0}", sub());
        }
    }

    class Tester
    {
        static void Main(string[] args)
        {
        //math1 m1 = new math1();
        math2 m2 = new math2();
            math3 m3 = new math3();
            //m1.operation();
           
            m2.operation();
            m3.operation();
            Console.ReadKey();
        }
    }
}



Tuesday, March 3, 2015

OOPs interface vs abstract class

InterfaceAbstract class
Interface support multiple inheritanceAbstract class does not support multiple inheritance
Interface does'n Contains Data MemberAbstract class contains Data Member
Interface does'n contains CunstructorsAbstract class contains Cunstructors
An interface Contains only incomplete member (signature of member)An abstract class Contains both incomplete (abstract) and complete member
An interface cannot have access modifiers by default everything is assumed as publicAn abstract class can contain access modifiersfor the subs, functions, properties
Member of interface can not be StaticOnly Complete Member of abstract class can be Static

Introduction

In this article along with the demo project I will discuss Interfaces versus Abstract classes. The concept of Abstract classes and Interfaces is a bit confusing for beginners of Object Oriented programming. Therefore, I am trying to discuss the theoretical aspects of both the concepts and compare their usage. And finally I will demonstrate how to use them with C#.

Background

An Abstract class without any implementation just looks like an Interface; however there are lot of differences than similarities between an Abstract class and an Interface. Let's explain both concepts and compare their similarities and differences.

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.

Both Together

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:
FeatureInterfaceAbstract class
Multiple inheritanceA class may inherit several interfaces.A class may inherit only one abstract class.
Default implementationAn interface cannot provide any code, just the signature.An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access ModfiersAn interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as publicAn abstract class can contain access modifiers for the subs, functions, properties
Core VS PeripheralInterfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.An abstract class defines the core identity of a class and there it is used for objects of the same type.
HomogeneityIf various implementations only share method signatures then it is better to use Interfaces.If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
SpeedRequires more time to find the actual method in the corresponding classes.Fast
Adding functionality (Versioning)If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and ConstantsNo fields can be defined in interfacesAn abstract class can have fields and constrants defined