Tag Archives: C#

C# Extension Methods


In this article, let’s know about CSharp Extension methods. Basically this feature was introduced in C# 3.0

Introduction

Extension methods enable you to “add” methods to existing types. They are special kind of static method. They make it possible to extend existing types with additional methods.

Extension methods are declared by specifying this keyword on the first parameter of the methods. Extension methods can only be declared in non-generic, non-nested static classes.

Examples

1. Extend “int” datatype.


public static class MyExtensions
{

  public static bool IsEvenNumber(this int number)

  {
    if (number % 2 == 0)
    {
     return true;
    }
     return false;
  }
 }

To call “IsEvenNumber” extension method from main, consider following code snippet.


class Program
 {
 static void Main(string[] args)
 {
 int i = 45;

 Console.WriteLine(i.IsEvenNumber());
 Console.ReadLine();
 }
 }

 

int-Extension

So in the example above, “IsEvenNumber” has became part of  int datatype and is accessible via intellisense.

2. Extend “string” datatype.


public static class MyExtensions
 {
public static bool IsNullOrEmpty(this string input)
{
if (input == null || input == string.Empty)
{
return true;
}
return false;
}

}

To call “IsNullOrEmpty” extension method from main, consider following code snippet.


class Program
 {
static void Main(string[] args)
{
string str = "";

Console.WriteLine(str.IsNullOrEmpty());
Console.ReadLine();
}
 }

 

string-Extension

So in the example above, “IsNullOrEmpty” has became part of string datatype and is accessible via intellisense.

You can even include the namespance of the Extension methods and reuse them anywhere in your project.

Source Code Download:

Github [Repository Link]

Box.com [Direct Download Link]

Related articles

Tuple in C# 4.0


A Tuple in C# is an ordered sequence, means each object being of a specific type. It is introduced in C# 4.0 with dynamic programming. It can be useful when returning more than one value from a method.

A Tuple has many items. Each item can have any data type. The Tuple class provides a unified syntax for creating objects with typed fields.

Visual studio provides the intellisense for tuple object depends upon the data type of the item.

Methods


//Creates a new 1-tuple, or singleton.
public class Tuple <T1>

//Creates a new 2-tuple, or pair.
public class Tuple <T1, T2>

//Creates a new 3-tuple, or triple.
public class Tuple <T1, T2, T3>

//Creates a new 4-tuple, or quadruple.
public class Tuple <T1, T2, T3, T4>

//Creates a new 5-tuple, or quintuple.
public class Tuple <T1, T2, T3, T4, T5>

//Creates a new 6-tuple, or sextuple.
public class Tuple <T1, T2, T3, T4, T5, T6>

//Creates a new 7-tuple, or septuple.
public class Tuple <T1, T2, T3, T4, T5, T6, T7>

//Creates a new 8-tuple, or octuple.
public class Tuple <T1, T2, T3, T4, T5, T6, T7, T8>

A Tuple can be instantiated in two ways:

1. Constructor


var tuple = new Tuple<int, string>(10, "Hello World");

2. Static method


var tuple = Tuple.Create(10.10, "Hello World", 50);

Tuples are commonly used in four ways:

1. To represent a single set of data. For example, a tuple can represent a database record, and its components can represent individual fields of the record.

2. To provide easy access to, and manipulation of, a data set.

3. To return multiple values from a method without using out parameters.

4. To pass multiple values to a method through a single parameter.

Example


Tuple<int, string> tuple = new Tuple<int, string>(10, "Hello World!");
Console.WriteLine(tuple.Item1); // will print 10
Console.WriteLine(tuple.Item2); // will print "Hello World!"

Sending E-mail Using ASP.NET


Description and steps:

1. I have created “EmailHelper” class which is very self explanatory.

2. Include the namespace “System.Net.Mail”.

using System.Net.Mail;

Please note: We can include “System.Web.Mail” or “System.Net.Mail“. These 2 namespaces contains classes used to send an email to a Simple Mail Transfer Protocol (SMTP) server for delivery.. But since “System.Web.Mail” is deprecated, It is recommended to use “”System.NET.Mail”.

Even if you can use “System.Web.Mail”, it is not a full .NET native implementation of the SMTP protocol. Instead, it uses the pre-existing COM functionality in CDONTS. System.Net.Mail, in contrast, is a fully managed implementation of an SMTP client.

3. In your Web.config file, include following lines.


<system.net>
<mailSettings>
<smtp from="defaultEmail@yourdomain.com" deliveryMethod="SpecifiedPickupDirectory">
<network host="localhost" port="25" userName="UserName" password="Password"/>
<specifiedPickupDirectory pickupDirectoryLocation="c:\Emails\"></specifiedPickupDirectory>
</smtp>
</mailSettings>
</system.net>

4. Create “Emails” folder on your C drive. P.S. You can create folder anywhere on your system, but path of the folder should be same as like in the web.config file.

5. Code snippet to send mail using “EmailHelper” class.


EmailHelper emailHelper = new EmailHelper("test@email.com", "recepient@email.com", null, null, "This email was sent from my asp.net application", string.Format("Email was sent on {0}<br/></b>This is bold text.</b><br/><I>This is italic</i>", DateTime.Now), true, System.Net.Mail.MailPriority.High);
emailHelper.SendMailMessage();

6. If you are running it locally, you need to configure SMTP on your system. If you don’t know how to do it, please refer the related article links at the bottom of this post.

EmailHelper Class Explained:

1. It contains 2 constructors. First one is default and other one is parameterised.

2. If you use the parameterised constructor while creating instance of the class, you can send mail as shows above by very simple way with only 2 lines of code.

3. It also contains a SendMailMessage method with 1 overload. First one with no input parameters and other one is with multiple parameters.

4. If you want to send emails to multiple users (e.g 2 users in TO, 2 users in CC, 3 users in Bcc etc), then SendMailMessage with multiple input parameter method is for you. Pass the list of persons as per your requirement and call the method.

5. It has one extra method called “IsValidEmailAdress”. It validates email ID’s using regular expressions.

Downloads:

Github [Repository Link]

Box.com [Direct Link to Zip file]

Access Modifiers In C#


It’s been always a confusion about the default access modifiers. Here is a small article which will make things clear.

Access Modifiers in C#:

public

The type or member can be accessed by any other code in the same assembly or another assembly.

private

The type or member can be accessed only by code in the same class or struct.

protected

The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly.

Default Access Modifiers in C#:

1. A class has default modifiers as Internal.

2. An enum has default modifier as public.

3. An interface has default modifier as public

4. Like class, A struct has default modifier as Internal.

5. A methods, fields, and properties has default access modifier as “Private” if no modifier is specified.