C# windows based application

The following program is a sample Windows Based C# application. Create a new C# Windows Application project and copy and paste the following source code.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void button1_Click(object sender, EventArgs e)
		{
			MessageBox.Show("This is my first program");
		}
	}
}

When you execute this C# program you will get the message “This is my first program” in a message box.

C# console based application

Console programs are easy to develop, because console based applications perform all their input and output at the command line, they are ideal for quickly trying out language features and writing command-line utilities. If you have ever learned a programming language, you know that they all start with the “Hello, world!” program. Here also we start with the “Hello, world!”. also check C# and JAVA

Hello World – Your First Program

In order to create a C# console based application

1. Open your Visual Studio

2. On the File menu, click New Project.

Then the New Project dialog box appears. This dialog box lists the different default application types.

3. Select Console Application as your project type and change the name of your application at the bottom textbox.

If you are npt comfortable with default location, you can always enter a new path if you want.

4. Then Click OK.

After click OK button, you will get a screen like the following picture.

Csharp console based application

Here in the following program, we just print a “Hello, world!” message only. So copy and paste the following command in the main code block. Also check C# and VB.NET

Console.WriteLine(“Hello, world!”);

Here you can see the full source code.

using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine(“Hello, world!”); } } }

After enter the command, the next step is to run the program. You can run your program using Ctrl+F5 . Then Visual Studio will keep the console window open, until you press a key. You will get screen look like the following picture.

Csharp console based application 1

Now you created your first program in Visual Studio.

How to stop C# console applications of closing automatically

The first program is to run your application by using Ctrl+F5, so the console window will remain open until you press a key. The disadvantage of this (Ctrl+F5) is that you lose Visual Studio’s debug information. If you run your console application by using F5 instead of Ctrl+F5 , you can see the window will disappear suddenly. It is because you program is finished. When console applications have completed executing and return from their main method, the associated console window automatically closes. This is expected behavior.

Prevent a C# Console Application from closing when it finishes

If you want to keep the application open for debugging purposes, you’ll need to instruct the computer to wait for a key press before ending the app and closing the window. In this case you can use Console.ReadLine() to wait for the user to Enter or Console.ReadKey to wait for any key.

Console.ReadLine(); Console.ReadKey();

Full Source:

using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine(“Hello, world!”); Console.ReadLine(); } } }

C# Command Line Parameters

In some situations, you have to send command line parameters to your application. When you pass arguments, the command line input, read from the standard entry point as string array.

static int Main(string[] args)

The arguments of the Main method is a String array that represents the command-line arguments. Usually you determine whether arguments exist by testing the Length property.

if (args.Length == 0) { System.Console.WriteLine(“No arguments found!!”); return 1; }

The main program accept arguments in the order of args[0], args[1] etc. The following program shows how to display all parameters enter to the console application.

using System; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine(“Number of command line arguments = {0}”,args.Length); for (int i = 0; i < args.Length; i++) { Console.WriteLine(“Arg[{0}] = [{1}]”, i, args[i]); } } } }

How to pause console application

System.Threading.Thread.Sleep() will delay your programs. It receives a value indicating the number of milliseconds to wait. This can be useful for waiting on an external application or task.

class Program { static void Main(string[] args) { Console.WriteLine(“Pausing 5 seconds”); System.Threading.Thread.Sleep(5000); } }

When you run the above program, it will wait for 5 seconds and exit from application.

How do I correctly exit from a console application

A console application will just terminate when it’s done, generally when it runs to the end of its Main entry point method. A “return” will achieve this.

C# and JAVA

C# and JAVA are two different Object Oriented Languages , both have a few similitudes and contrasts too. The Csharp and JAVA got from their own particular single predecessor Class “Protest”. All Classes in C# are dropped from System.Object Class and in JAVA all classes are subclasses of java.lang.Object Class. C# tries to be present day, to sparkle with new elements, to ride early, to embrace obscure punctuation for things. C# is increasingly a “business” dialect with numerous intense libraries financially accessible. While Java tries to be moderate, gradually embracing new things, steady, clear, plain, effortlessly understandible by a beginner. Java is more like an “opensource” dialect with tons and huge amounts of opensource libraries accessible.

C# and JAVA
C# and JAVA

Also Read: C# and VB.NET

Runtime Environments

Both C# and JAVA have their own runtime surroundings . C# source codes are incorporated to Microsoft Intermediate Language (MSIL) and amid the execution time runs it with the assistance of runtime conditions – Common Language Runtime (CLR). Like that JAVA source codes are accumulated to Java Byte Code and amid the execution time runs it with the assistance of runtime conditions – Java Virtual Machine (JVM). Both CSharp and JAVA bolsters local assemblage by means of Just In Time compilers.

Sort Safe Languages

Java and C# were intended to be type-safe . An illicit throwing will be gotten at assemble time in the event that it can be demonstrated that the cast is unlawful; or an exemption will be tossed at runtime if the question can’t be thrown to the new sort. Sort wellbeing is in this way more vital in light of the fact that it not just powers a developer to compose more right code, yet in addition enables a framework to end up noticeably more secure from code programmers.

Refuse Collection

In bring down level dialects, memory administration can be dull work since you need to make sure to appropriately erase new protests free up assets. That is not the case in C# and Java , where worked in refuse gathering avoids memory spills by evacuating objects that are never again being utilized by the application. While memory breaks can even now happen, the fundamentals of memory administration have just been dealt with for you.

Generics

Generics enhance compiler-helped checking of sorts to a great extent by expelling throws from source code. In Java, generics are actualized utilizing erasures. Generic type parameters are “deleted” and gives occasion to feel qualms about are included aggregation into bytecode. C#takes generics considerably promote by coordinating it into the Common Language Infrastructure (CLI) and permitting sort data to be accessible at runtime, yielding a slight execution pick up.

Pointers

C# permits the utilization of pointers, which some dialect creators consider to be risky, yet certain dialect highlights attempt to guarantee this usefulness is not abused accidentally. Pointers also extraordinarily confound advances, for example, Java’s Remote Method Invocation (RMI), where program objects occupant on one PC can be referenced inside a program running on a totally isolate PC. Some have conjectured that the absence of memory pointers in Java was a gesture towards the happening to lattice registering, where a solitary application might be disseminated crosswise over numerous physical bits of equipment.

Techniques

Techniques in c-sharp are non-virtual as a matter of course. In Java be that as it may, techniques are virtual as a matter of course. Virtual techniques ensure that the most superseded strategy for a protest will be called which is controlled by the runtime . You generally need to remember that when calling or composing any virtual technique! On the off chance that the technique is announced as non-virtual, the strategy to conjure will be controlled by the compiler. This is a noteworthy distinction of reasoning between the creators of the Java and .NET stages.

C# and VB.NET

CSharp and VB.NET are the two primary languages used to program on the .NET Framework environment. Both languages are use the same framework and they both precompiled into the same byte code and then it is compiled and run at runtime. So we can say VB.NET and C# are functionally equivalent. Both C# and Visual Basic.NET share structural similarities with other modern high level languages such as Java and C++ .

C# and VB.NET
C# and VB.NET

But both have different in many features. Primarily keywords are different in each other language . C# is case sensitive while Visual Basic .NET is not. In VB.NET “Example” and “example” are same , but in CSHARP “Example” and “example” are two different variable names. Also it is good to remember that C# statements always terminated by a semicolon (;). More On CSharp

The following are some examples of differences between VB.NET and C#.

Single Line Comments :

  VB.NET	: ' ex: 'This is a single line comment
  CSHARP		: // ex: //This is a single line comment

Multi Line Comments :

  VB.NET	: Not available
  CSHARP		: /*..*/	ex: /*Multi line comments */

Conditional Statements

VB.NET

  If condition Then
	  'vb.net code
  Else
	  'vb.net code
  End If

CSHARP

  if(condition)
  {
	  //csharp code
  }
  else
  {
	  //csharp code
  }

Loops

VB.NET

  For counter As Integer = 0 To final
	  'vb.net code
  Next

CSHARP

  for(int i=0;i < final;i++)
  {
	  //csharp code
  }

Operator (Equal)

VB.NET

  a=b

CSHARP

  a==b;

Declaration

VB.NET

  Dim i as Integer = 10

CSHARP

  int i=10;

 

Iterators in C#

In this article, we will discuss:

  • Iterators in C#
  • Iterator Blocks
  • Yield Statements
  • Using an Iterator to Create an Enumerator
  • Using an Iterator to Create an Enumerable
  • Common Iterator Patterns
  • Creating Multiple Enumerables
  • Iterators As Properties
  • Behind the Scenes with Iterators
  • An Iterator state machine
  • Summary

 

Iterators in C#

In the previous article we have discussed on Enumerable classes and enumerators and the difference between IEnumerator and IEnumerable Interface in C#.

C# language provides a construct for creating Enumerators and Enumerables in simpler way and that is Iterator.By using Iterators, compiler will create Enumerators and Enumerables for you. You can use the enumerators and enumerables generated by iterators wherever you would use manually coded enumerators orenumerables.Iterators require the System.Collections.Generic namespace. More On CSharp

Let’s look at below example.

The following method declaration is another version that produces the same result:
Return an enumerator that returns strings.

you might have the feeling that something is different about this code. It doesn’t seem quite right. What exactly does the yield return statement do?

For example, in the first version, if the method returns on the first yield return statement, then the last two statements can never be reached. If it doesn’t return on the first statement, but continues through to the end of the method, then what happens to the values?

And in the second version, if the yield return statement in the body of the loop returns on the first iteration, then the loop will never get to any subsequent iterations. And besides all that, an enumerator doesn’t just return all the elements in one shot—it returns a new value with each access of the Current property. So, how does this give you an enumerator? Clearly this code is different from anything shown before.

Let’s understand the iterator blocks and yield statements to answer all these questions.

Iterator Blocks:

An iterator block is a code block with one or more yield statements. There are 3 types of Iterator blocks.

  • A method body
  • An accessor body
  • An operator body

In regular code blocks, the first statement in the block is executed, followed by the subsequent statements, and eventually control leaves the block but in iterator block,it describes the behavior of the enumerator class you want the compiler to build for you and it describes how to enumerate the elements.

Iterator blocks have two special statements:
• The yield return statement specifies the next item in the sequence to return.
• The yield break statement specifies that there are no more items in the sequence.

You can have the iterator produce either an enumerator or an enumerable depending on the return type you use for the iterator block.

 

 

Using an Iterator to Create an Enumerator:

Output:

black
red
white

Description:

  • Method Color is an iterator block that produces a method that returns an enumerator for class MyClass.
  • MyClass also implements method GetEnumerator, which just calls Color, and returns the enumerator that Color returns to it.
  • In Main, you can use an instance of the class directly in the foreach statement since the class implements GetEnumerator and is therefore enumerable.

 

Using an Iterator to Create an Enumerable:

Output:

black red white black red white

Description:

  • In the previous example, iterator method Color returned an IEnumerator, and MyClass implemented method GetEnumerator by returning the object created by Color.
  • In this example, the iterator method Color returns an IEnumerable rather than an IEnumerator. MyClass, therefore,implements its GetEnumerator method by first calling method Colors to get the enumerable object and then calling that object’s GetEnumerator method and returning its results.
  • Notice that in the foreach statement in Main, you can either use an instance of the class or call Color directly, since it returns an enumerable.

 

Common Iterator Patterns

Mainly there are 2 Iterator Patterns.
1.Enumerator Iterator Patterns
2.Enumerable Iterator Patterns

    • When you implement an iterator that returns an enumerator, you must make the class enumerable by implementing GetEnumerator
    • In a class, when you implement an iterator that returns an enumerable, you can make this class itself enumerable.

− If you implement GetEnumerator, make it call the iterator method to get an instance of the automatically generated class that implements IEnumerable.Next, return the enumerator built by GetEnumerator from this IEnumerable object
− If you decide against making the class itself enumerable, by not implementing GetEnumerator, you can still use the enumerable returned by the iterator, by calling the iterator method directly.

 

Creating Multiple Enumerables

Output:

 

Iterators as Properties:

Output:

 

Description:

In the above example,

  • It uses iterators to produce a class with two enumerators.
  • It shows how iterators can be implemented as properties rather than methods.
  • The code declares two properties that define two different enumerators. The GetEnumerator method returns one or the other of the two enumerators, depending on the value of the Boolean variable _listFromUVtoIR. If _listFromUVtoIR is true, then the UVtoIR enumerator is returned. Otherwise, the IRtoUV enumerator is returned.

 

Behind the Scenes with Iterators in C#

The enumerator class generated by the compiler is a state machine with four states:
• Before: The initial state before the first call to MoveNext.
• Running: The state entered when MoveNext is called. In this state, the enumerator determines and sets the position for the next item. It exits the state when it encounters a yield return, a yield break, or the end of the iterator body.
• Suspended: The state where the state machine is waiting for the next call to MoveNext.
• After: The state where there are no more items to enumerate.

Summary:

In this article, we have discussed:

  • Iterators in C#
  • Iterator Blocks
  • Yield Statements
  • Using an Iterator to Create an Enumerator
  • Using an Iterator to Create an Enumerable
  • Common Iterator Patterns
  • Creating Multiple Enumerables
  • Iterators As Properties
  • Behind the Scenes with Iterators
  • Iterator StateMachine
  • An Iterator state machine

You may also like :

Thanks for visiting !!

async & await keyword in C#

In this article, we will discuss:

  • What is an async Method?
  • The Flow of Control in an Async Method
  • The await Expression
  • Exception Handling and the await Expression
  • Cancelling an async Operation
  • Waiting Asynchronously for Tasks in the async Method
  • Summary

 

What is an async Method?

An async method is a method that returns to the calling method before completing all its work, and then completes its work while the calling method continues its execution.

An async method has the following characteristics: More On CSharp

  • An async method must have the async keyword in its method header, and it must be before the return type.
  • This modifier doesn’t do anything more than signal that the method contains one or more await expressions.
  • It contains one or more await expressions. These expressions represent tasks that can be done asynchronously.
  • It must have one of the following three return types.
    − void :If the calling method just wants the async method to execute, but doesn’t need any further interaction with it
    − Task : If the calling method doesn’t need a return value from the async method, but needs to be able to check on the async method’s state
    − Task<T> :If the calling method is to receive a value of type T back from the call, the return type of the async method must be Task
  • An async method can have any number of formal parameters of any types but it cannot be out or ref parameters.
  • The name of an async method should end with the suffix Async.
  • Otherthan Methods, lambda expressions and anonymous methods can also act as async objects.

 

Using an async method that returns a Task<int> object:

Output:

 

Using an async method that returns a Task object:

Output:

Value: 21
Async stuff is done

Using an async method that returns a void object:

Output:

Value: 21
Program Exiting

The Flow of Control in an Async Method :

The body of an async method has divided mainly into three sections.

  • Before the first await expression : This includes all the code at the beginning of the method up until the first await expression. This section contains very minimal code that doesn’t require too much processing.
  • The await expression: This expression represents the task to be performed asynchronously.
  • Continuation: This is the rest of the code in the method, following the await expression. This includes the information about which thread it’s on, the values of the variables currently in scope, and other things it’ll need in order to resume execution later, after the await expression completes

The code in the async method does the following:

  • It executes, asynchronously, its await expression’s awaitable task.
  • When the await expression is done, it executes the continuation.
  • The continuation itself might have other await expressions, which are handled the same way. That is, the await expression is executed asynchronously, followed by the execution of its continuation.
  • When the continuation encounters a return statement or the end of the method:
    • If the method’s return type is void, the flow of control exits.
    • If the method’s return type is Task, the continuation sets the status properties on the Task and exits. If the return type is a Task<T>, the continuation additionally sets the Result property of the Task object.

 

The await Expression:

The await expression specifies a task to be done asynchronously.

Syntax:

There are now a number of BCL methods that return objects of type Task<T>, you’ll most likely have your own methods that you want to use as the task for an await expression. The easiest way to do that is to create a Task from your method using the Task.Run method.

the most important fact about the Task.Run method is that it runs your method on a different thread.
One signature of the Task.Run method is,it takes a Func delegate as a parameter.

So, to pass your method to the Task.Run method, you need to create a delegate from it.

There are three ways to do this.

In the code, method Get20 has a form compatible with a Func<int> delegate since it takes no parameters and returns an int.

  • In the first instance, which is in the first two lines of method DoWorkAsync, a Func delegate named twenty is created using Get20. That delegate is then used in the Task.Run method in the next line.
  • In the second instance, a Func delegate is created right in the Task.Run method’s parameter list.
  • The last instance doesn’t use the Get20 method at all. It uses the return statement that comprises the body of the Get20 method, and uses it as the body of a lambda expression compatible with a Func<int> delegate. The lambda expression is implicitly converted to the delegate.

 

 

Exception Handling and the await Expression:

You can use await expression inside atry statement.

Output:

Cancelling an async Operation :

You can cancel your own async operation.There are two classes in the System.Threading.Tasks namespace that are designed for this purpose: CancellationToken and CancellationTokenSource.

  • A CancellationToken object contains the information about whether a task should be cancelled or not.
  • A task that has a CancellationToken object needs to periodically inspect it to see what the token’s state is. If the CancellationToken object’s
    IsCancellationRequested property is set to true, the task should halt its operations and return.
  • A CancellationToken is nonreversible and can only be used once. That is, once it’s IsCancellationRequested property is set to true, it can’t be changed.
  • A CancellationTokenSource object creates a CancellationToken object, which can then be given to various tasks. Any objects holding a cancellationTokenSource can call its Cancel method, which sets the CancellationToken’s IsCancellationRequested property to true.

 

Output:

If you uncomment the Thread.Sleep and Cancel statements in method Main, the task is cancelled after three secondsand below is the output:

 

Waiting Asynchronously for Tasks in the async Method:

In your async method, if you want to wait on Tasks as your await expression. This allows your async method to return to the calling method, but allows the async method to wait for completion of one or all of a set of tasks. The calls that allow this are the Task.WhenAll and Task.WhenAny methods.

 

Output:

 

Summary:

In this article, we have discussed:

  • What is an async Method?
  • The Flow of Control in an Async Method
  • The await Expression
  • Exception Handling and the await Expression
  • Cancelling an async Operation
  • Waiting Asynchronously for Tasks in the async Method
  • Summary

You may also like:

Thanks for visiting !!

SOLID Design Principles C#

In this article, we will learn SOLID principles in C#:

 

  • What is Single Responsibility Principle (SRP)

  • What is Open Closed Principle (OCP)

  • What is Liskov Substitution Principle (LSP)

  • What is Interface Segregation Principle (ISP)

  • What is Dependency Inversion Principle (DIP)

 

1. What is Single Responsibility Principle (SRP)?

The single responsibility principle states that every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class.

All its services should be narrowly aligned with that responsibility

As per SRP, there should not be more than one reason for a class to change, or a class should always handle single functionality. If you put more than one functionality in one Class in C# it introduce coupling between two functionality and even if you change one functionality there is chance you broke coupled functionality, which require another round of testing to avoid any surprise on production environment. More On CSharp

2. What is Open Closed Principle (OCP)?

In object-oriented programming, the open/closed principle states “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification”; that is, such an entity can allow its behaviour to be extended without modifying its source code.

Open Closed principle helps you write code that is extensible and cleaner.

3. What is Liskov substitution principle (LSP) ?

The Liskov substitution principle (LSP) is a particular definition of a subtyping relation, called (strong) behavioral subtyping, that was initially introduced by Barbara Liskov in a 1987 conference keynote address entitled Data abstraction and hierarchy

  • if S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program

In order to follow this principle we need to make sure that the subtypes respect the parent class.

4. What is Interface Segregation principle (ISP) ?

The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use.

  • ISP splits interfaces which are very large into smaller and more specific ones so that clients will only have to know about the methods that are of interest to them.
  • ISP is intended to keep a system decoupled and thus easier to refactor, change, and redeploy.

ISP is one of the five SOLID principles of Object-Oriented Design, similar to the High Cohesion Principle of GRASP

5. What is Dependency Inversion principle (DIP) ?

The Dependency Inversion principle refers to a specific form of decoupling software modules.It states:

  • High-level modules should not depend on low-level modules. Both should depend on abstractions.
  • Abstractions should not depend on details. Details should depend on abstractions.

The Dependency Inversion principle (DIP) helps us to develop loosely couple code by ensuring that high-level modules depend on abstractions rather than concrete implementations of lower-level modules

Thanks for visiting !!

Top 10 new features of C#6.0

In this article, we will learn top 10 new features of C# 6.0.

1. Static Using Syntax:

Before C# 6.0, In a console application if you wanted to print something, then you would write the following line of code:

In C# 6, you can now add the using static qualifier and reference the WriteLine method by itself as shown below:

This will also work for custom classes created by yourself. Let’s look at the below example. More On CSharp

Since you have declared CustomClass with the static keyword, you can run the method by just calling the method name. The output for this sample program would be :

 

2. String Interpolation :

String Interpolation is a mechanism to concatenate two or more strings together.In older versions of C#, we were using “+” operator or String.Format method to concatenate strings but in C# 6.0, Microsoft has provided a feature named String Interpolation to concatenate strings.

Using “+” Operator:

 

Using String.Format method:

 

New ways of String Concatenation in C#6.0

The output for this program will be:

 

3. Exception Filters:

Earlier Exception filters were supported in Visual Basic but not in C#. They allow you to specify a condition for a catch block.

 

In C#6.0, without entering the catch block, you can check to see which condition met your exception.

 

 

4. Await in a Catch and Finally Block:

In C# 6, now you can write asynchronous code inside a catch/finally block. This will help you to log exceptions to a file or database without blocking the current thread. Let’s look at below example:

 

5. Null Conditional Operator:

Most of us do not like NullReferenceException . Let’s look at below example, on how to handle NullReferenceException prior to C#6.0.

If you enter some data into name, then the console prints out that name else this returns “Field is null”.

New ways to handle NullReferenceException in C#6.0:

In C# 6.0, you can use ?. to check if an instance is null or not. Let’s look at below example to see how it works in C#6.0.

 

6. Auto Property Initializer:

Prior to C#6.0, we were using constructor to initialize the auto properties to non-default value.

In C#6.0, you can modify the Employee class and populate the property called EmployeeID with inline initialization.

The output for this sample will be a random guid generated by the system.

7. Dictionary Initializers:

In C# 5, you would initialize the Dictionary with a {“Key”, “Value”} Pair. Let’s look at below example to understand it better.

 

In C# 6, you can place the key between two square brackets [“Key”] and then set the value of the key [“Key”] = “value”.

 

8.Expression Bodied Function & Property:

Expression Bodied Functions are functions with no statement body. Instead, you implement them with an expression following the function declaration

The result of the above program would be 10.

9. Getter-only Auto Properties:

When you use auto implemented properties in C# 5 and lower, you must provide a get and set. If you want the property value to be immutable, you can use the private accessor on the setter. With C# 6, you can now omit the set accessor to achieve true readonly auto implemented properties:

10. NameOf Expression:

Name of Expression is a new feature introduced in C#6.0.In Enterprise level applications, we handle exceptions at different levels.Showing a specific type name with an error message can be an easy way to find the code block where the exception just occurred. But by adding this we can’t show it to user because the type name can be changed anytime while refactoring but hard coded string won’t change accordingly.

Before C# 6.0 :

What happens if someone changes the Title variable to newTitle? Since we hard-coded the “Title is null” error, that is what will appear to the end-user. We would rather it now say, “newTitle is null”, but the compiler cannot recognize this.

In C# 6.0, we can refactor our code to remove the string literals and use the nameof expression.

 

 

Summary:

In this article, we have discussed top 10 new features introduced in C# 6.0.
– Auto Property Initializer
– Await in a Catch and Finally Block in C#6.0
– Dictionary Initializers in C# 6.0
– Exception Filters in C#6.0
– Expression Bodied Function & Property in C#6.0
– Getter-only Auto Properties in C#6.0
– NameOf Expression in C#6.0
– Null Conditional Operator in C#6.0
– Static Using Syntax in C#6.0
– String Interpolation in C#6.0
Thanks For visiting !!

C# 7.0 – Tuples

In this article, we will discuss on Tuple Class in C# and the potential new proposals that is being considered for C#7.

What is Tuple in C#?

A tuple is a data structure that has a specific number and sequence of elements.

A tuple allows you to combine multiple values of possibly different types into a single object without having to create a custom class. This can be useful if you want to write a method that for example returns three related values but you don’t want to create a new class. More On CSharp

System.Tuples namespace supports Tuple class in C#.

The purpose of a tuple is to create a way to return multiple values from a function.

Example:

 

Output:

Create Tuple using Tuple.Create method :

 

Output:

Tuple that returns multiple values in C#:

 

Output:

 

When to use Tuples in C#?

Tuples are commonly used in four ways:

  • 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.
  • To provide easy access to, and manipulation of, a data set.
  • To return multiple values from a method without using out parameters
  • To pass multiple values to a method through a single parameter. For example, the Thread.Start(Object) method has a single parameter that lets you supply one value to the method that the thread executes at startup time. If you supply a Tuple<t1, t2,=”” t3=””> object as the method argument, you can supply the thread’s startup routine with three items of data.</t1,>

Issues on Tuple Class:

Member Names:

The main problem with Tuple class is it’s Member Names. It does not have any Semantic meaning.

If you see a return type of Tuple<int, int=””> that doesn’t really tell you anything.</int,>

So it is difficult to understand and maintain the code. It would be far more useful if the return type were something like Tuple

So in C#7, Tuples would probably have names, as it makes identifying each member of the Tuple easier.

Let’s look at below example to understand the C#7 proposal on Tuples.

There are 2 proposals being considered for how tuples would be returned from function:

Tuples and Async :

You can use Tuples with Async.

References:
https://github.com/dotnet/roslyn/issues/2136

In the next article, we will discuss on C#7, potential feature: Pattern matching.

Thanks for visiting !!

C# 7.0 – Local Functions

In this article, we will discuss one of the planned language features in C# 7.0

Local functions are functions that you define inside another function. C#7.0 will allow you to declare functions in the body of other functions.

Like Lambda expressions, Parameters and local variables from the enclosing scope are available inside of a local function.

Example:

Methods implemented as iterators need a non-iterator wrapper method for checking the arguments at the time of the call. More On CSharp

If Iterator had been a private method next to Employee, it would have been available for other members to accidentally use directly (without argument checking). Also, it would have needed to take all the same arguments as Employee instead of having them just be in scope.

Advantage of using Local Functions:

– Like lambdas, local functions can capture local variables and parameters of their containing method
– Local functions support recursion like any normal methods
– They don’t require you to allocate a delegate to hold them. This reduces memory pressure and also allows the function to be in-lined by the compiler.
– They don’t require you to allocate an object when creating a closure because it has access to the local variables. Also, this improves performance by reducing GC pressure.
You can read more planned C#7.0 features here.

You can try this feature yourself using Visual Studio 15 Preview 4.

Please Note, In visual studio 15 Preview 4, local functions must be declared before they are called. This restriction will be loosened, so that they can be called as soon as local variables they read from are definitely assigned.

Thanks for Visiting!!