Named Parameter's | this Keyword


Previous Articles - "ReadOnly" Fields | "Ref" & "Out" Parameter's

Named Parameters :

  • This feature is introduced in C#.NET 4.0.
  • This is used to pass the arguments to the method, with those names.

C# Coding on Named Parameters :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 namespace NamedParametersDemo
  {
   class User
   {
    //fields
    public string FirstName;
    public string LastName;
    //methods
    public void SetUserName(string FirstName, string LastName)
     {
      this.FirstName = FirstName;
      this.LastName = LastName;
     }
    public void ShowUserName()
     {
      Console.WriteLine(FirstName + " " + LastName);
     }
   }

 class Program
  {
    static void Main(string[] args)
     {
       User u = new User();
       u.SetUserName(LastName: "Kumar", FirstName: "Raj"); //call a method, with 
       named parameters
       u.ShowUserName();
       Console.Read();
     }
  }
}

this Keyword :

  1. This is similar to "this pointer" in C++.
  2. It represents current working object.
  3. It is used to access the members of current working object.
    • this.field
    • this.property
    • this.method()
  4. Current object : The object, with which object, the method is called.
  5. "this" keyword can‘t be used in the static methods, because static methods doesn‘t have current object.

C# Coding on this Keyword :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 namespace ThisKeywordDemo
  {
   class Sample
   {
    //fields
    public int n = 100;
    //methods
    public void Increment()
     {
      int n = 10; //incrementation value
      this.n = this.n + n;
     }
   }

   class Program
    {
      static void Main(string[] args)
       {
        Sample s = new Sample();
        Console.WriteLine(s.n);
        s.Increment();
        Console.WriteLine(s.n);
        Console.Read();
       }
    }
  }

Previous Articles - "ReadOnly" Fields | "Ref" & "Out" Parameter's
Tag : C#, C# Tutorials
0 Komentar untuk "Named Parameter's | this Keyword "

Back To Top