Posts Tagged ‘C#’

29
Jun

Prepend method in LINQ

Yesterday I needed to put one element at beginning of the collection I already had. Some kind of Concat upside down. :) As you can use the Concat method, it looks weird when you see the code, because two items are actually swapped. So I created a simple extension method to do it for me.

I started with:

public static IEnumerable<T> Prepend<T>(this IEnumerable<T> source, T item)
{
	yield return item;
	foreach (var x in source)
		yield return x;
}

It’s classic imperative approach, you’re expressing how you’ll do it. Then I thought: “Hey, why not to use LINQ methods already available.”. As you guess, I abused Concat method as I wrote above:

public static IEnumerable<T> Prepend<T>(this IEnumerable<T> source, T item)
{
	return new[] { item }.Concat(source);
}

You can easily extend both methods to accept also collection as a second parameter.

If you’re more about declarative programming you’ll probably like the other one. But choose whatever fits your brain better.

  • Twitter
  • Facebook
  • Share/Bookmark
26
Jun

How to break your code easily a.k.a my params hell

Today I faced a behavior I have no idea exists. It’s more or less ambiguity between method with some parameters and one using params. Why more or less? Well, because it surely described in C# specification (“best match” or something similar to it). But I hadn’t know I should think about it until I was debugging weird behavior.

Let’s start with simple class:

class Test
{
	public Test(params int[] foos)
	{
		Console.WriteLine("foos");
	}

	public Test(int foo, int bar)
	{
		Console.WriteLine("foo bar");
	}
}

And now some (mind blowing ;) ) code:

new Test(1);
new Test(1, 2);
new Test(1, 2, 3);

If you see the code in the context you probably spot the problem easily. The second row will not call the params but the other constructor.

Which is “cool” until you’re doing some refactoring and you (as I did) add new constructor with params and everything starts behaving unexpectedly. Maybe this text will help somebody to realize this faster than I did. :D

  • Twitter
  • Facebook
  • Share/Bookmark
6
Jun

Running the other method on same thread as the first one

Last week I was solving problem. The piece of code another code was plugged in was doing some crazy threading stuff inside while the code plugged in used some component that needed some methods (in my case just two) to be called in same thread. Well, that is to make the long story short.

As I couldn’t rely on the fact, that the thread calling the first method will be still available when the other one needs to be called I decided to simply steal one thread (in fact ThreadPool thread) for it a abuse it exclusively. To encapsulate this hack I created this class.

Before you dive into, I have to note, that it is really not a general purpose class and you shouldn’t blindly use it – you can easily use it badly and i.e. create unwanted shared state, screw the flow of your program or get wrong results due race conditions, …

/// <summary>
/// This is NOT a general purpose class.
/// Use with care.
/// </summary>
sealed class ThreadMethodRunner : IDisposable
{
	AutoResetEvent _eventMethodDone;
	AutoResetEvent _eventMethodIn;
	Action _method;

	public ThreadMethodRunner()
	{
		_eventMethodDone = new AutoResetEvent(false);
		_eventMethodIn = new AutoResetEvent(false);
		ThreadPool.QueueUserWorkItem(new WaitCallback(MethodRunnerWrapper), null);
	}

	private void MethodRunnerWrapper(object o)
	{
		for (int i = 0; i < 2; i++)
		{
			Debug.WriteLine("Waiting for method");
			_eventMethodIn.WaitOne();
			Action a = Interlocked.Exchange(ref _method, null) as Action;
			a();
			Debug.WriteLine("Method done");
			_eventMethodDone.Set();
		}
		Debug.WriteLine("Thread done");
	}

	public void Do(Action method)
	{
		Interlocked.Exchange(ref _method, method);
		_eventMethodIn.Set();
		_eventMethodDone.WaitOne();
	}

	public void Dispose()
	{
		_eventMethodDone.Dispose();
		_eventMethodIn.Dispose();
	}
}

This class allows you to call the Do method with Action delegate and the method will run the code on the same thread every time (in my case just two times) called. This method blocks as you probably want to keep the behavior of you old code (at least in boundaries of method calls order, not changing some state etc. as mentioned above).

I don’t know if it’s worth any other usage than mine, but at least somebody may be inspired.

  • Twitter
  • Facebook
  • Share/Bookmark
15
May

T4 templates processing at runtime

The T4 templates are great tool for use. You can generate literally anything with it with comfort of using any .NET code you have available. Code generation (i.e. POCO classes in EFv4), web service proxies, simple DALs, …, all easily available.

But what if your scenario is one step further? You don’t want to use T4 template to generate i.e. code you’ll later compile into your application, but use the T4 template in runtime to generate result your application will later use (i.e. email based on template). Good news is you can do it, and it’s not hard either.

Easiest way is to start with Preprocessed Text Template file type adding to your solution. The file itself is ordinary T4 template you’re familiar with. But if you build your project the result produced isn’t output from template, but the C#/VB code that produces the result if called. Same result can be done by changing Custom Tool into TextTemplatingFilePreprocessor in Properties window of your current T4 template file.

Then you can create instance of this class (it has same name as your template file), setting up properties, if any and calling TransformText method. Pretty easy, isn’t it?

  • Twitter
  • Facebook
  • Share/Bookmark
28
Aug

Using custom properties as parameters in queries (in EF)

Most of the time you’re using properties in objects that are also in database. But sometimes you may need to create property in object that’s not in database – it’s used only in this application or it’s there custom logic. Then, if you wanna use it in queries, you’re out. You can use only those properties declared in table, obviously.

But there’s a solution. First, the property has to be created from some other properties, so you’re able to do the same in database. And of course, functions used there needs to be translatable to store language too. This may limit you, but there’s nothing you can do about it, except evaluating query on client side.

Let’s have a table like this:

create table Foo (
  ID int primary key,
  IsAccepted bit,
  IsPaid bit not null,
  IsPacked bit not null,
);

And you wanna have property IsReadyToShip, in application. So you create:

public bool IsReadyToShip
{
  get { return this.IsAccepted.HasValue && this.IsAccepted && this.IsPaid && this.IsPacked; }
}

But with this property you’re not able to query for all Foos ready to ship. Luckily the solution is pretty easy. First you’ll create expression for this:

public static Expression<Func<Foo, bool>> IsReadyToShipExpression = f => f.IsAccepted.HasValue && f.IsAccepted && f.IsPaid && f.IsPacked;

Then you’l prepare static compiled version of this expression, just for performance reasons, you can compile it in getter everytime too:

protected static Func<Foo, bool> IsReadyToShipFunc = IsReadyToShipExpression.Compile();

And finally the property:

public bool IsReadyToShip
{
  get { return IsReadyToShipFunc(this); }
}

Right now we have the same result as before – working property. But because we also have the expressions of the property (and incidentally it’s translatable to store language ;) ), so we can use it for querying. You can use it in an easy way (this is in this case ObjectContext used in Entity Framework):

public IQueryable<Foo> FoosReadyToShip
{
  get { return this.Foos.Where(Foo.IsReadyToShipExpression); }
}

Not the shortest way to do it. But if you don’t wanna to write the condition again and again (and lower the maintainability) this is a way to do it.

  • Twitter
  • Facebook
  • Share/Bookmark
26
Aug

Singleton shortcut

Probably every developer sometimes heard about the singleton pattern. I’ll be not far from truth that you’re probably writing it like this:

class Foo1
{
	private static Foo1 _instance;

	public static Foo1 Instance
	{
		get
		{
			if (_instance == null)
				_instance = new Foo1();

			return _instance;
		}
	}
}

I do it same way. But today I seen little bit different way. It’s using the C# coalesing operator and some C-like magic syntax.

class Foo2
{
	private static Foo2 _instance;

	public static Foo2 Instance
	{
		get
		{
			return _instance ?? (_instance = new Foo2());
		}
	}
}

Looks cool, isn’t it? On the other hand I’ll probably use the first one, as it’s more readable, at least for me.

  • Twitter
  • Facebook
  • Share/Bookmark
8
Jul

Is array[0] vs. array[] { } the same?

Today I was writing some code, where I needed create initially empty array. I wondered if the array[0] vs. array[] { } is the same. Alike with the string concatenation.

Without writing further text. Lines:

private static void Test1()
{
	string[] s1 = new string[0];
	Console.WriteLine(s1);
}
private static void Test2()
{
	string[] s2 = new string[] { };
	Console.WriteLine(s2);
}

resulted in this IL:

.method private hidebysig static void  Test1() cil managed
{
  // Code size       14 (0xe)
  .maxstack  1
  .locals init ([0] string[] s1)
  IL_0000:  ldc.i4.0
  IL_0001:  newarr     [mscorlib]System.String
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  call       void [mscorlib]System.Console::WriteLine(object)
  IL_000d:  ret
} // end of method Program::Test1
.method private hidebysig static void  Test2() cil managed
{
  // Code size       14 (0xe)
  .maxstack  1
  .locals init ([0] string[] s2)
  IL_0000:  ldc.i4.0
  IL_0001:  newarr     [mscorlib]System.String
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  call       void [mscorlib]System.Console::WriteLine(object)
  IL_000d:  ret
} // end of method Program::Test2

As you (and I) can see, the code is the same (I was kind of expecting that – but what’s better proof than IL?). So you don’t need to worry using the first or the other syntax.

  • Twitter
  • Facebook
  • Share/Bookmark
4
Jul

New IStructuralEquatable, IStructuralComparable and StructuralComparisons

.NET Framework 4 comes with (among others) with two new interfaces. IStructuralEquatable and IStructuralComparable. These are implemented (right now in Beta 1) by Array and Tuple(s).

With this new implementations and StructuralComparisons you can check arrays and tuples for structural equality (or compare these).

object[] o1 = new object[] { 1, "2" };
object[] o2 = new object[] { 1, "2" };

Console.WriteLine(o1.Equals(o2));
Console.WriteLine(o1.Equals(o2, StructuralComparisons.StructuralEqualityComparer));

The code above writes first false and then true. The first one is classic “old-school” Equals. Following line is using new structural comparison, thus the true as result. Neat, isn’t it?

By the way, F# is now using these interfaces too.

  • Twitter
  • Facebook
  • Share/Bookmark
20
May

is, as, != null

Po diskuzi v postu if, else, return jsem si uvědomil, že mám v kapse ještě jeden případ, který je podobně sporný-zajímavý. Tyto dvě konstrukce vídávám a opět v zásadě stejné – nebo ne?

Foo x = (y as Foo);
if (x != null)
{
  x...
}
else
{
  // <error>
}

resp. (samozřejmě můžeme i přiřadit do x)

if (y is Foo)
{
  (y as Foo)...
}
else
{
  // <error>
}

Osobně používam druhý způsob, opět spíše pocitově něž pro nějaký fakt (myslím, že z toho is je výsledek mého snažení lépe čitelný). A co vy? Případně máte nějaký argument proč používat jedno nebo druhé?

  • Twitter
  • Facebook
  • Share/Bookmark
14
May

if, else, return

Občas vidím ve zdrojácích funkce s konstrukcí:

if (<condition>)
{
  x = DoSomething(y);
  return x;
}
return z;

Což je víceméně to samé jako:

if (<condition>)
{
  x = DoSomething(y);
  return x;
}
else
{
  return z;
}

Osobně používám druhý zápis. Přijde mi o něco přehlednější a explicitnější. Pravděpodobně vliv Delphi/ObjectPascalu.

Je však v těchto zápisech nějaký rozdíl? Nějaký praktický aspekt, který mi uniká?

  • Twitter
  • Facebook
  • Share/Bookmark
9
May

C# obsesión – how many characters you are able to put into type? :)

I was writing some return type from function when I got brilliant dumb idea to start playing with braces, question marks etc. :) And I came with some self-competition to write a lot of different characters into a valid type definition (in C#, of course). And simple repeating doesn’t count. But why not to create this as a public competition. ;)

With the short first try I ended up with this:

IEnumerable<KeyValuePair<int, int?>?[,]>

That’s probably not the best what can be done. Do you have better idea? OK, it’s your turn. Use comments. The best – I’m the referee – will get the lolipop.

Sorry for all spanish speaking people if the word in title isn’t right.

  • Twitter
  • Facebook
  • Share/Bookmark