How Yield keyword works in C#

Yield in C# , can use with the return statement to build a collection of returns. For example , I have a method that we need to return a collection of integers in a lazy manner and expose it through an IEnumerable interface. Based on the value produce with the yield return , consumer can write some logic based on their need.

In the below example you can see I have a method ReturnSomeIntegers() , which return 1 to 10 by iterate using for loop with yield keyword and also two more yield return with 20 and 30 respectively.

class Program
static void Main(string[] args)


static void YieldDemo()
foreach ( int n in ReturnSomeIntegers())
if (n == 20)
Console.WriteLine("From Yield Return Two - " + n);
else if (n == 30)
Console.WriteLine("From Yield Return Three - " + n);
Console.WriteLine("From Yield Return One - " + n);
private static IEnumerable ReturnSomeIntegers()
for(int i = 1; i <= 10; i++)
yield return i;
yield return 20;
yield return 30;

Whenever ReturnSomeIntegers() method return a single value , the execution will switchback to YieldDemo() for each method and print the value based on the condition.

In Computer Science this is known as Continuation

Show Image using byte array in WPF

Convert your image in to byte array
private byte[] GetImageAsByteArray(string imageName)
var streamResourceInfo =
Application.GetResourceStream(new Uri("YourProjectNameSpace;component/ImageFolderName/"+imageName)",
byte[] image = {};
if (streamResourceInfo != null)
var length = streamResourceInfo.Stream.Length;
image = new byte[length];
streamResourceInfo.Stream.Read(image, 0, (int)length);
return image;

Sample Usage
var yourViewModel = new ViewModel();

Bind the property to the image control

<Image Source=”{Binding Image}”></Image>

How Layout Process works in WPF?

Before you design the layout you need to understand what’s going behind the scenes when you create layouts in your applications. If you have knowledge about the layout process, you know what happens with your elements and you can build really great layouts.

The Layout process is two step process. It consists of the steps Measure andArrange . In the first step, the Measure step elements calculate their desired size.That means each element calculate their own size.To do this an element calls the Measure method in each direct child.After this , the DesiredSize property of the child is set. The parent element can access this DesiredSize and calculate it’s own desired size.The whole process walks down the element tree so it starts at the parent element,which calls measure on each direct child and each direct child again calls Measure on its direct children.
In the second step,the Arrange step,elements arrange their children. They do this by calling Arrange method on each direct child.The Arrange method takes a position and a final size.That means child knows the position for render and size as well.After the two process rendering occurs.

Theil’s Inequality Algorithm using C#


public class TheilInEqualityAlgorithm
private readonly int _holdOutPeriod;
private readonly IEnumerable _actualAndPredictedValues;
public TheilInEqualityAlgorithm(int holdOutPeriod, IEnumerable actualAndPredictedValues)
_holdOutPeriod = holdOutPeriod;
_actualAndPredictedValues = actualAndPredictedValues;
private double CalculateRootMeanSquareDeviation()
double sum = 0;
foreach (ActualAndPredictedValue actualAndPredictedValue in _actualAndPredictedValues)
double difference = actualAndPredictedValue.Actual - actualAndPredictedValue.Predicted;
double squareOfdifference = Math.Pow(difference, 2);
sum = sum + squareOfdifference;

double rootMeanSquareDeviation = Math.Sqrt(sum / _holdOutPeriod);
return rootMeanSquareDeviation;
public Dictionary<string,double> CalculateTheilInEquality()
var results=new Dictionary<string, double>();
double calculatedRootMeanSquareDeviation = CalculateRootMeanSquareDeviation();
double actualSquareSum = 0;
double predictedSquareSum = 0;
foreach (ActualAndPredictedValue actualAndPredictedValue in _actualAndPredictedValues)
double actualSquare = Math.Pow(actualAndPredictedValue.Actual, 2);
double predictedSquare = Math.Pow(actualAndPredictedValue.Predicted, 2);
actualSquareSum = actualSquareSum + actualSquare;
predictedSquareSum = predictedSquareSum + predictedSquare;
double sqrtOfActualSum = Math.Sqrt(actualSquareSum / _holdOutPeriod);
double sqrtOfPredictedSum = Math.Sqrt(predictedSquareSum / _holdOutPeriod);
double theilInEquality = (calculatedRootMeanSquareDeviation) / (sqrtOfActualSum + sqrtOfPredictedSum);
results.Add("TheilInEquality", theilInEquality);
return results;
public class ActualAndPredictedValue
public double Actual { get; set; }
public double Predicted { get; set; }

Pass actual and predicted values for the periods

var actualPredictedCollection = new List
new ActualAndPredictedValue
Actual =-659505.150000,
Predicted =-900587.246911
var results = new TheilInEqualityAlgorithm(12,actualPredictedCollection).CalculateTheilInEquality();
double theilInEquality=results[“TheilInEquality”];
Enjoy coding…

Change Telerik GridViewCellColor based on value

You can change Gridview cell color based on a value by using CellStyleSelector in GridViewDataColumn.
First you have to add a class by inheriting StyleSelector and override SelectStyle method
public class MyStyle:StyleSelector
public override Style SelectStyle(object item, DependencyObject container)
if(item is Student)
var objEntity = item as Student;
if (objEntity.Mark > 60)
return Green;

return null;
public Style Green { get; set; }
Add a Grid Resource

<my:MyStyle x:Key="myStyle">
<Style TargetType="telerik:GridViewCell">
<Setter Property="Background" Value="Green" />



Apply the style to GridViewDataColumn CellStyleSelector Attribute

<telerik:GridViewDataColumn DataMemberBinding="{Binding Mark}" CellStyleSelector="{StaticResource myStyle}">

Happy coding…

How to Catch Exceptions thrown by a WCF service In Client

You can easily get the server side Unhandled exceptions thrown by a WCF service in Client by using FaultException

Set includeExceptionDetailInFaults to true in your service behaviours

<behavior name=””>
<serviceMetadata httpGetEnabled=”false” />
<serviceDebug includeExceptionDetailInFaults=”true” />

and then in client side you can catch exceptions like below
//your service call
catch (FaultException ex)
string msg = "FaultException: " + ex.Message;
MessageFault fault = ex.CreateMessageFault();
if (fault.HasDetail)
System.Xml.XmlReader reader = fault.GetReaderAtDetailContents();
if (reader.Name == "ExceptionDetail")
var detail = fault.GetDetail<Exception>();
msg += "\n\nStack Trace: " + detail.StackTrace;

Enjoy Programming…