What We Do

  • Our Focus is You
    We focus on your online needs so that you can focus on your customer's needs. There are numerous way in which we can help you. We begin by reviewing your business goals, your marketing objectives, and your competitive position, and then we develop your online presence to meet your needs.
  • Dynamic Content
    Today's web applications require dynamically driven content, and much of that content is provided by a database and a programming language operating in harmony to produce the desired results. MySQL and PHP are two of the most popular web development tools utilized to produce dynamic web sites. We can help you take control and begin building truly dynamic web content which is easier to maintain, is more responsive to your users, and can alter its appearance based upon differing situations. Contact Us today to discuss your custom development needs.
  • Content Management Systems (CMS)
    We can deploy CMS applications to allow organizations to edit content easily, which significantly cuts down on costly professional maintenance fees. Our CMS expertise covers Joomla, Wordpress and Blogger platforms. We are ready to help you choose which works best for your specific needs. Contact Us today to begin taking control of your content.
Powered by Blogger.

C# Basic Syntax (Classes, Objects, and Methods)

C# is an object-oriented programming language. In Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions. The actions that an object may take are called methods. Objects of the same kind are said to have the same type or, more often, are said to be in the same class.

For example, let us consider a Rectangle object. It has attributes like length and width. Depending upon the design, it may need ways for accepting the values of these attributes, calculating area and display details.

Let us look at an implementation of a Rectangle class and discuss C# basic syntax, on the basis of our observations in it:

using System;
namespace RectangleApplication
{
    class Rectangle
    {
        // member variables
        double length;
        double width;
        public void Acceptdetails()
        {
            length = 4.5;    
            width = 3.5;
        }
        public double GetArea()
        {
            return length * width;
        }
        public void Display()
        {
            Console.WriteLine("Length: {0}", length);
            Console.WriteLine("Width: {0}", width);
            Console.WriteLine("Area: {0}", GetArea());
        }
    }
    
    class ExecuteRectangle
    {
        static void Main(string[] args)
        {
            Rectangle r = new Rectangle();
            r.Acceptdetails();
            r.Display();
            Console.ReadLine();
        }
    }
}
When the above code is compiled and executed, it produces the following result:

Length: 4.5
Width: 3.5
Area: 15.75

The using Keyword

The first statement in any C# program is

using System;
The using keyword is used for including the namespaces in the program. A program can include multiple using statements.

The class Keyword

The class keyword is used for declaring a class.

Comments in C#

Comments are used for explaining code. Compilers ignore the comment entries. The multiline comments in C# programs start with /* and terminates with the characters */ as shown below:

/* This program demonstrates
The basic syntax of C# programming 
Language */
Single-line comments are indicated by the '//' symbol. For example,

}//end class Rectangle  

Member Variables

Variables are attributes or data members of a class, used for storing data. In the preceding program, the Rectangle class has two member variables named length and width.

Member Functions

Functions are set of statements that perform a specific task. The member functions of a class are declared within the class. Our sample class Rectangle contains three member functions: AcceptDetails, GetArea and Display.

Instantiating a Class

In the preceding program, the class ExecuteRectangle is used as a class, which contains the Main() method and instantiates the Rectangle class.

Identifiers

An identifier is a name used to identify a class, variable, function, or any other user-defined item. The basic rules for naming classes in C# are as follows:

A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.

It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.

It should not be a C# keyword.

C# Keywords

Keywords are reserved words predefined to the C# compiler. These keywords cannot be used as identifiers; however, if you want to use these keywords as identifiers, you may prefix the keyword with the @ character.

In C#, some identifiers have special meaning in context of code, such as get and set, these are called contextual keywords.

The following table lists the reserved keywords and contextual keywords in C#:
Reserved Keywords
abstractasbaseboolbreakbytecase
catchcharcheckedclassconstcontinuedecimal
defaultdelegatedodoubleelseenumevent
explicitexternfalsefinallyfixedfloatfor
foreachgotoifimplicitinin (generic
modifier)
int
interfaceinternalislocklongnamespacenew
nullobjectoperatoroutout
(generic
modifier)
overrideparams
privateprotectedpublicreadonlyrefreturnsbyte
sealedshortsizeofstackallocstaticstringstruct
switchthisthrowtruetrytypeofuint
ulonguncheckedunsafeushortusingvirtualvoid
volatilewhile
Contextual Keywords
addaliasascendingdescendingdynamicfromget
globalgroupintojoinletorderbypartial
(type)
partial
(method)
removeselectset

Objects

An object is basically a block of memory that has been allocated and configured according to the blueprint. A program may create many objects of the same class. Objects are also called instances, and they can be stored in either a named variable or in an array or collection.

An Object in C# is an instance of a class that is created dynamically. Object is also a keyword that is an alias for the predefined type System.Object in the .NET framework.   The unified type system of C# allows objects to be defined. These can be user-defined, reference or value type, but they all inherit directly or indirectly from System.Object. This inheritance is implicit so that the type of the object need not be declared with System.Object as the base class.

In general, object type is useful where there is a requirement to build generic routines. Because values of any type can be assigned to variables of object type, object type is used mostly in designing classes that handle objects of any type that allow code to be reused. The non-generic collection classes in the .NET framework library, such as ArrayList, Queue, etc., use object type to define various collections.

Methods

A method is a group of statements that together perform a task. Every C# program has at least one class with a method named Main.

To use a method, you need to:

  • Define the method
  • Call the method

Defining Methods in C#

When you define a method, you basically declare the elements of its structure. The syntax for defining a method in C# is as follows:

<Access Specifier> <Return Type> <Method Name>(Parameter List)
{
   Method Body
}
Following are the various elements of a method:

  • Access Specifier: This determines the visibility of a variable or a method from another class.
  • Return type: A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void.
  • Method name: Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class.
  • Parameter list: Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.
  • Method body: This contains the set of instructions needed to complete the required activity.
Example:
Following code snippet shows a function FindMax that takes two integer values and returns the larger of the two. It has public access specifier, so it can be accessed from outside the class using an instance of the class.

class NumberManipulator
{
   public int FindMax(int num1, int num2)
   {
      /* local variable declaration */
      int result;

      if (num1 > num2)
         result = num1;
      else
         result = num2;

      return result;
   }
   ...
}

Calling Methods in C#

You can call a method using the name of the method. The following example illustrates this:

using System;

namespace CalculatorApplication
{
   class NumberManipulator
   {
      public int FindMax(int num1, int num2)
      {
         /* local variable declaration */
         int result;

         if (num1 > num2)
            result = num1;
         else
            result = num2;

         return result;
      }
      static void Main(string[] args)
      {
         /* local variable definition */
         int a = 100;
         int b = 200;
         int ret;
         NumberManipulator n = new NumberManipulator();

         //calling the FindMax method
         ret = n.FindMax(a, b);
         Console.WriteLine("Max value is : {0}", ret );
         Console.ReadLine();
      }
   }
When the above code is compiled and executed, it produces the following result:

Max value is : 200

You can also call public method from other classes by using the instance of the class. For example, the method FindMax belongs to the NumberManipulator class, you can call it from another class Test.

using System;

namespace CalculatorApplication
{
    class NumberManipulator
    {
        public int FindMax(int num1, int num2)
        {
            /* local variable declaration */
            int result;

            if (num1 > num2)
                result = num1;
            else
                result = num2;

            return result;
        }
    }
    class Test
    {
        static void Main(string[] args)
        {
            /* local variable definition */
            int a = 100;
            int b = 200;
            int ret;
            NumberManipulator n = new NumberManipulator();
            //calling the FindMax method
            ret = n.FindMax(a, b);
            Console.WriteLine("Max value is : {0}", ret );
            Console.ReadLine();

        }
    }
}
When the above code is compiled and executed, it produces the following result:

Max value is : 200

Recursive Method Call

A method can call itself. This is known as recursion. Following is an example that calculates factorial for a given number using a recursive function:

using System;

namespace CalculatorApplication
{
    class NumberManipulator
    {
        public int factorial(int num)
        {
            /* local variable declaration */
            int result;

            if (num == 1)
            {
                return 1;
            }
            else
            {
                result = factorial(num - 1) * num;
                return result;
            }
        }
    
        static void Main(string[] args)
        {
            NumberManipulator n = new NumberManipulator();
            //calling the factorial method
            Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6));
            Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
            Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
            Console.ReadLine();

        }
    }
}
When the above code is compiled and executed, it produces the following result:

Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320

Passing Parameters to a Method

When method with parameters is called, you need to pass the parameters to the method. In C#, there are three ways that parameters can be passed to a method:

MechanismDescription
Value parametersThis method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
Reference parametersThis method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument.
Output parametersThis method helps in returning more than one value.