Showing posts with label .net beginners tutorial. Show all posts
Showing posts with label .net beginners tutorial. Show all posts

26 December 2015

difference between value type and reference type

Recently I got a chance to talk to a bunch of entry level professionals working on a software development project. During the discussion, a question came up on what is value type, what is a reference type and what is the difference between the two. Answer I got for those questions weren't satisfactory.

So at that moment I thought let me blog on this topic, so that other similar students can read and enhance their knowledge on difference between the value type and reference types in simple words with relevant tutorial examples.

What is a value type?

When you pass a variable to a method, if the variable value gets passed instead of the variable itself, then they are called value types. Didn't understand?. Don't worry, let's consider an example.

public static void Main(string[] args)
{
int salary = 1000;
IncrementSalary(salary, 100);
Console.Writeline(salary);
}

public statis IncrementSalary(int salary, int byAmount)
{
salary = salary + byAmount;
}

What is the output of the above C#.NET example?

  • Is it 1000?
  • Is it 1100?

Actual output

1000

If your answer was 1100, then your understanding of value types is incorrect. Read further to understand, "What is a value type"?

When you call a method "IncrementSalary" and the pass the variable "salary" to it, actually an another variable, which is

  • pointing to a different memory location than that of salary variable
  • AND
  • having the same value of the salary variable

is passed.

So whatever variable value gets updated inside the "IncrementSalary" method, the value stored in the new memory location will get updated. Hence updates to the variable will not be reflected in the caller method's variable (i.e., Main() method in this case)

Examples of value types in .NET C#

More or less all structures, i.e, int, decimal, DateTime, long etc

What is reference type?

When you pass a variable to a method, if the variable reference gets passed to the passed to the method parameter then they are called reference types. Let's consider a sample C# .NET tutorial example.

public class PromotionOffer{
public int Discount {get;set;}
}

public static void Main(string[] args
{
PromotionOffer offer = new PromotionOffer();
offer.Discount = 10;
IncrementOfferDiscount(offer, 10);
Console.Writeline(offer.Discount);
}

public static IncrementOfferDiscount(PromotionOffer offer,
                                     int byPercenatge)
{
offer.Discount += byPercentage;
}

What is the output of the above C#.NET example?

  • Is it 10?
  • Is it 20?

Actual output

20

If your answer was 10, then your understanding on reference type is incorrect. Read further to understand, "what is a reference type".

When you call the method "IncrementOfferDiscount" and pass in the promotionOffer variable, the method gets the same reference of the variable used by the calling method(in this case, it is Main() method). So whenever you update the properties of the reference type variable in the method called, it will update the same copy of the values held by the calling method.

So after you call the IncrementOfferDiscount() method and print the Discount of promotionOffer object, you will see the updated value 20.

Examples of reference types in .NET C#

All inbuilt classes in the .NET framework and custom classes you define are reference types.

Now I hope you understood what is value type, what is reference type and the difference between value type and reference type.

Note:
  • The built-in String class is a reference type, but .NET framework treats it differently, because of string intern concept(which is same in JAVA as well)
  • The value types can be passed to a method as reference types using out and ref keywords. Learn more about ref and out keywords in C# .NET by reading my another post "ref v/s out in .NET"

27 September 2015

debugging Web Applications hosted in IIS using Visual Studio

In the past 1 month, I have explained 3 people on how to debug web applications (ASP.NET, ASP.NET MVC) and Web services (ASMX, WCF services) hosted in IIS using Visual Studio IDE. So thought it would be beneficial for the developers who are beginners in .NET Web Application development.

Steps to debug Web Apps running in IIS using VS IDE

(Assuming you have already hosted your web application in IIS)
  1. Open the web application solution in the Visual Studio as an Admin and build it. Ensure the web site browse-able by using URL hosted in IIS.
  2. Now in the DEBUG menu in the toolbar click on the "Attach to Process" menu item (alternatively you can also use shortcut key Ctrl+Alt+P combination) to open the "Attach to Process" window.
  3. Ensure you check the check-boxes "Show Process from All users" and "Show process in all sessions" in the "Attach to Process" window. This will ensure you will start seeing the W3WP.EXE process in the list.
  4. Now find the W3WP.EXE process with the Application pool same as your Web Application is using.

    The Username column indicate the application pool for which the W3WP.EXE corresponds to.

    In this case the Application pool is "ASP.NET v4.0".

  5. Select the right W3WP.EXE process and click on "Attach" button. In the "Attach Security Warning" click Attach.
  6. Then add a breakpoint to the line of code you wish to debug and browse the URL which hit that line of code.

    Before the line code is going to get executed, your breakpoint will be hit and you will able to debug your application.

13 September 2015

avoiding the execution of finally block of code in C# .NET

We all know that finally block of code is always going to get executed irrespective of whether there is an exception or not. Thereby finally() block of code helps to clean any resources held up by the code.

But, there is one exception to the above rule.

The finally block of code will not get executed, when the code executes Environment.FailFast() method.

static void Main(string[] args)
{       
  try
  {
    Environment.FailFast("Message logged!");
  }
  catch (Exception ex)
  {
                    
  }
  finally
  {
    Console.WriteLine("finally executed...");
  }
}

Whenever Environment.FailFast() method gets executed, it immediately terminates a process after it writes the message to the Windows Application Event log!

You can see the below error logged into Windows Application log.

Application: FailFast.exe Framework Version: v4.0.30319 Description: The application requested process termination through System.Environment.FailFast(string message). Message: Message logged! Stack: at System.Environment.FailFast(System.String) at FailFast.Program.Main(System.String[])

06 September 2015

Installing IIS on windows 7 machine

.NET beginners who are working on ASP.NET web application development, may need to host their website on IIS web server. Below are the simple steps to install the IIS 7 on Windows 7 Operating system.

You need to be a System Administrator on your machine to install the IIS (Internet Information Service) or you need to take the help of System Admin to install the service.

  1. Open Program and Features window (Start Menu => Control Panel =>Program and Features)
  2. On the left side click on the "Turn Windows features on or off" link button. You will see a "Turn Windows features on or off" windows.
    Installing IIS using Turn windows features on or off
  3. Under the "Internet Information Services" node select whatever features you want and click on OK button. It takes a while, once it's completed you can launch the IIS Manager using the start menu or using the "inetmgr" command in the RUN window (Windows Key + R).

29 December 2013

c# class tutorial

Classes are ubiquitous in Object-Oriented Programming & Systems. Classes are very important in C# programming as well; we cannot assume a single program in OOPS without class. Then let's go through the tutorial, class in C#.

  1. What are classes?
  2. Defining a class in C#
  3. What constitutes a class with C# class example
  4. Types of classes in C#

What are classes?

Let's take an example of a real-world entity. You ask your friend, which movie they last saw? One friend might say, "I saw Hindi movie Dhoom3 - Aamir Khan acting suburb, Krishna Acharya has directed, one & half hour long and U/A certificate etc".

So the movie entity has Name, Actors, Director, Duration and U/A, etc attribute and these attributes define a movie. If you ask another friend, more or less he will also give the details of the movies in the form of same attributes. So A set of attributes are defining a movie and these set of attributes vary from movie to movie.

If movie entity has to be represented in OOPS, we could create Movie Class with all the common attributes defined as properties; and create different movies like Dhoom3, Titanic, Avatar, etc. So, varying values for set of attributes are defining different movies.

So, classes are the nothing but a template or blueprint used to create objects/instances of a certain entity. We can also say a class represents, an entity and defines how their the different instances looks and behaves.

Defining a class in C#

public class Movie
{
   
}
  • In C# .NET, a class will be defined using the class keyword.
  • Every class will have name;in the above C# code sample, class name is Movie.
  • The class will have its entire definition defined within the { flower brackets }.

What constitutes a class with C# class example

In short class will have a name, attributes defined as properties, behaviors /capabilities defined as methods and constructors to create instances of the class.

Let's go through an example of class, SmtpClient to understand what constitutes a class. SmtpClient class is under System.net.Mail namespace which is present in .NET framework. In an high level the SmtpClient class looks like below:

namespace System.Net.Mail
{
   public class SmtpClient
    {
     // Properties which defines class.
      public string Host { get; set; }
      public int Port { get; set; }

      // Constructor to create class instance
      public SmtpClient(string host, int port)
      { 
        // Constructor logic the goes here...
      }
 
      public void Send(string from,string recipients,
                       string subject,string body) 
      {
       // method logic goes here...
      }
       
    }
}
  • Class name: In the above c# code sample, SmptClient is the class name. Class name used to uniquely identify a class.
    public class SmtpClient
  • Namespace: Namespace used to group related classes together. Class names should be unique in a given namespace. In the above C# class example, System.Net.Mail is the namespace.
  • namespace System.Net.Mail
  • Properties: Properties helps to build a instance of the class. If you have two different set of values for a given entity, two different instances/objects will be created; i.e class instances vary by their properties values.
    public string Host { get; set; }
    public int Port { get; set; }

    The above C# class code sample, has two properties Host & Port.

    Consider another example of Person class. Two different persons will have different name, profession, address, etc. So name, profession and address, etc represent a Person. Hence Person class developer defines class with Name, Profession and Address as properties.

  • Constructors: Constructors are special methods in a class used to create an instance of the class.
    public SmtpClient(string host, int post)
      { 
            // Constructor logic the goes here...
      }

    Constructors should take all the required/mandatory parameters as arguments; So that, after you have the objects created using constructors, the object should be usable and shouldn't throw exceptions when a method is invoked using the object.

  • Methods: The capabilities of a class will be exposed as methods. For example, in the above SmtpClient class, Send() method sends the email out.
    public void Send(string from,string recipients,
                     string subject,string body) 
      {
           // method logic goes here...
      }

    The Send() method takes parameters which tells, what an email should be sent and for whom an email should be sent. i.e method arguments defines how the capabilities of the class will be used to get the desired result.

  • Class access specifier: Last but not the least, SmtpClient is defined with public access specifier. Meaning its visible to all.
    public class SmtpClient

    We can specify different access specifiers for the class i.e. public, internal, private, etc

Types of classes in C#

In C# we can define classes as static, abstract, sealed and partial. Let's go through one by one:

  • Abstract class: Abstract classes cannot be instantiated. These are mainly created to act as base class.
  • Static class: Static classes cannot be instantiated and no one can inherit from static classes. Mainly used to act as helper classes.
  • Sealed class: Sealed classes cannot be inherited. In case if you don't want to make class to be inherited, consider marking a class as sealed .
  • Partial class: Partial classes is not really a different type of class. Partial classes allows some part of the class definition coded in file and another part of the class coded in different file.

    For example, partial classes are used by Visual Studio Windows form designer, where in which form designer partial class will be generated by Visual Studio and code behind partial class is created by developer.