Posted on : 07-09-2009 | By : manitra | In : C#
0
The version 3 of C# brings us a lot of syntactic sugar to reduce the length of our code. Here are some of them.
This post is part of a serie about making C# code shorter.
Constructors with Property initializers
-
//Verbose and Ugly
-
Post value = new Post();
-
value.Title = "New Version For C#";
-
value.CreatedOn = DateTime.Now;
-
CreatePost(value);
-
-
//Concise and Sweet
-
CreatePost(new Post
-
{
-
Title = "NewVersion For C#",
-
CreatedOn = DateTime.Now
-
});
Collection initializers
-
//Verbose and Ugly
-
var names = new List<string>();
-
names.Add("manitra");
-
names.Add("yeah");
-
SaveNames(names);
-
-
//Concise and Sweet
-
SaveNames(new List<string> { "manitra", "yeah" });
Var keyword
-
//Verbose and Ugly
-
Dictionary<string, List<Post>> result = new Dictionary<string, List<Post>>();
-
-
//Concise and Sweet (But still trongly typed)
-
var result = new Dictionary<string, List<Post>>();
Automatic properties
-
//Verbose and Ugly
-
public class Post
-
{
-
private string title;
-
private string description;
-
private DateTime createdOn;
-
-
public string Title
-
{
-
get
-
{
-
return this.title;
-
}
-
set
-
{
-
this.title = value;
-
}
-
}
-
-
public string Description
-
{
-
get
-
{
-
return this.description;
-
}
-
set
-
{
-
this.description = value;
-
}
-
}
-
-
public System.DateTime CreatedOn
-
{
-
get
-
{
-
return this.createdOn;
-
}
-
set
-
{
-
this.createdOn = value;
-
}
-
}
-
}
-
-
//Concise and Sweet
-
public class Post
-
{
-
public string Title { get; set; }
-
public string Description { get; set; }
-
public DateTime CreatedOn { get; set; }
-
}
Posted on : 03-09-2009 | By : manitra | In : C#
0
Exception handling is an important part of any software. In this post, I will talk about a trick to make but some kind of reusability on exception handling.
This post is part of a serie about making C# code shorter
When you write code, you usually try to reuse your code by creating methods and calling those methods each time you the need their functionality. When working with exceptions, it’s a bit tricky because, they don’t follow the normal code flow, they jump out of your method … unless you catch them. The consequence is that you usually have multiple similar try {} catch {} blocks that are often copied and pasted.
This is what usually happens
-
public void Method1()
-
{
-
try
-
{
-
//method 1 content
-
}
-
catch (ThreadAbortException)
-
{
-
}
-
catch (IOException ex)
-
{
-
//IO exception handling
-
}
-
finally
-
{
-
//add any code for releasing ressource
-
}
-
}
-
-
public void Method2()
-
{
-
try
-
{
-
//method 2 content
-
}
-
catch (ThreadAbortException)
-
{
-
}
-
catch (IOException ex)
-
{
-
//IO exception handling
-
}
-
finally
-
{
-
//add any code for releasing ressource
-
}
-
}
The solution to reuse the exception block
This is what you could do to reuse the same error handling code block in c# :
-
public void Method1()
-
{
-
Do(() =>
-
{
-
//method 1 content
-
});
-
}
-
-
public void Method2()
-
{
-
Do(() =>
-
{
-
//method 2 content
-
});
-
}
-
-
protected void Do(Action method)
-
{
-
try
-
{
-
//code to call before each methods
-
method();
-
//code to call after each methods success
-
}
-
catch (ThreadAbortException)
-
{
-
}
-
catch (IOException ex)
-
{
-
//IO exception handling
-
}
-
finally
-
{
-
//add any code for releasing ressource
-
}
-
}
Posted on : 27-08-2009 | By : manitra | In : C#
0
Because, short code is easier to understand, I decided to publish some posts about making C# code shorter. I’ll talk about small tricks I use to significantly reduce the amount of code I write to achieve my goals. Some people don’t agree with that idea because there has been abuses done by perl and c programmer in the past. I think that, if you use correct names for methods, variable and types, the shortest code will still be easy to understand.
This post is part of a serie about making C# code shorter
In this post, I’ll use the following class for my examples :
-
public class Post
-
{
-
public int Id { get; set; }
-
public string Author { get; set; }
-
public string Title { get; set; }
-
public string Content { get; set; }
-
}
Linq extension methods
Linq is a set of contracts (interfaces) wich allow the developper to request objects from a data store. What make it unique is that :
- the query language is strongly typed (at compile time you are sure that all column names et types are corrects and that there are no missin semi-colon
- it supports unlimited data store type (including all database systems, xml files, google data, twitter posts, in memory objects …)
I’ll focus primarily on Linq to Objects (in memory object) because we’re talking about making code concise. So here are the shortcuts !
Searching an unique element in a collection
-
//Concise and Sweet
-
public Post GetById(int id, IList<Post> posts)
-
{
-
return posts.FirstOrDefault(p => p.Id == id);
-
}
-
-
//Verbose and Ugly
-
public Post GetById(int id, IList<Post> posts)
-
{
-
foreach (Post current in posts)
-
{
-
if (current.Id == id)
-
{
-
return current;
-
}
-
}
-
}
Filtering a collection
-
//Concise and Sweet
-
public IList<Post> FindByAuthor(string author, IList<Post> posts)
-
{
-
return posts.Where(p => p.Author == author).ToList();
-
}
-
-
//Verbose and Ugly
-
public IList<Post> FindByAuthor(string author, IList<Post> posts)
-
{
-
List<Post> result = new List<Post>();
-
foreach (Post current in posts)
-
{
-
if (current.Author == author)
-
{
-
result.Add(current);
-
}
-
}
-
return result;
-
}
Selecting a column (one property of an object collection)
-
//Concise and Sweet
-
public IList<string> ExtractTitles(IList<Post> posts)
-
{
-
return posts.Select(p => p.Title).ToList();
-
}
-
-
//Verbose and Ugly
-
public IList<string> ExtractTitles(IList<Post> posts)
-
{
-
List<string> result = new List<string>();
-
foreach (Post current in posts)
-
{
-
result.Add(current.Title);
-
}
-
return result;
-
}
Apply changes to a collection
-
//Concise and Sweet
-
public IList<Post> Anonymize(IList<Post> posts)
-
{
-
return posts.Select(p => new Post
-
{
-
Id = p.Id,
-
Title = p.Title,
-
Author = "***",
-
Content = p.Content
-
}).ToList();
-
}
-
-
//Verbose and Ugly
-
public IList<Post> Anonymize(IList<Post> posts)
-
{
-
List<Post> result = new List<Post>();
-
foreach (Post current in posts)
-
{
-
Post anonymousPost = new Post();
-
anonymousPost.Id = current.Id;
-
anonymousPost.Title = current.Title;
-
anonymousPost.Author = "***";
-
anonymousPost.Content = current.Content;
-
result.Add(anonymousPost);
-
}
-
return result;
-
}
Creating your own extension methods
Extension methods are the best candidates when you plan to build your very own low level toolset. Here are some examples to give you an idea.
-
public static class MyExtensions
-
{
-
//Index a collection by its key
-
public static IDictionary<TKey, TObject> IndexBy<TObject, TKey>(this IEnumerable<TObject> target, Func<TObject, TKey> keyExtractor)
-
{
-
-
var result = new Dictionary<TKey, TObject>();
-
foreach (var current in target)
-
result[keyExtractor(current)] = current;
-
return result;
-
}
-
-
//Joining any collection of string (array, list, enumerable …)
-
public static string Join(this IEnumerable<string> elements, string separator)
-
{
-
return string.Join(separator, elements.ToArray());
-
}
-
}
Posted on : 11-05-2009 | By : manitra | In : C#, Developpement, WinForm
2
The problem
When you create winform applications, doing tasks in the background is essential to avoid user frustation. Unfortunatly, it could make you write a lot more code. Here are some utility methods that reduce the complexity of asynchronous calls within windows forms.
Within you base class
You probably have a common base class for all your UI components. Add these methods :
-
namespace TestWinForm
-
{
-
public class BaseForm : Form
-
{
-
// Execute some code in async mode.
-
// When it's done, it calls the nextStep delegate, eventually with
-
// an exception catched during the main action.
-
protected virtual void Async(Action action, Action nextStep)
-
{
-
new Thread(delegate()
-
{
-
Exception exception = null;
-
try
-
{
-
action();
-
}
-
catch (Exception ex)
-
{
-
exception = ex;
-
}
-
ThreadSafe(() => { nextStep(exception ); });
-
}).Start();
-
}
-
-
// This allows a sub class to easily run a method within
-
// an UI thread without the need of creating multiple
-
// delegate signatures for each method signatures
-
protected virtual void ThreadSafe(MethodInvoker method)
-
{
-
if (InvokeRequired)
-
Invoke(method);
-
else
-
method();
-
}
-
}
-
}
Within your UI classes
Now the only thing you need to do is to encapsulate the methode content with the Async() method :
namespace TestWinForm
-
{
-
public partial class MainForm : BaseForm
-
{
-
public MainForm()
-
{
-
InitializeComponent();
-
}
-
-
// Here is the async trick :
-
// – UI will NOT freeze,
-
// – you can add beautifull animated gifs
-
private void button1_Click(object sender, EventArgs e)
-
{
-
DateTime? result = null;
-
Async(
-
() =>
-
{
-
result = GetComplexDate();
-
},
-
(ex) =>
-
{
-
if (ex == null)
-
textBox1.Text = result.Value.ToShortDateString();
-
else
-
textBox1.Text = ex.Message;
-
}
-
);
-
}
-
-
// This is the slow, data-intensive task :p
-
private DateTime? GetComplexDate()
-
{
-
Thread.Sleep(3000);
-
return DateTime.Now;
-
}
-
}
-
}
The traditional way
Just in case you didn’t get it. This is what you should NOT DO:
// This was traditional way :
-
// – UI will freeze until during 3 second …
-
// – you users will complain
-
// avoid this !
-
private void button1_Click2(object sender, EventArgs e)
-
{
-
try
-
{
-
textBox1.Text = GetComplexDate().ToShortDateString();
-
}
-
catch (Exception ex)
-
{
-
textBox1.Text = ex.Message;
-
}
-
}
Happy coding !
Posted on : 23-01-2009 | By : manitra | In : C#, Developpement, WinForm
5
The problem
If you’re working on WinForms, you must know that you cannot call controls methods within a thread that is not the one that created those controls. To solve this problem, Microsoft recommend us to use the following code :
-
namespace TestWinForm
-
{
-
public partial class MainForm : BaseForm
-
{
-
public MainForm()
-
{
-
InitializeComponent();
-
}
-
// a delegate that has been created specially for this method
-
private delegate void DisplayDelegate(string text);
-
-
// a method that may be called from a worker thread
-
public virtual void Display(string text)
-
{
-
if (InvokeRequired)
-
{
-
Invoke(new DisplayDelegate(Display));
-
}
-
else
-
{
-
//the actual job is here
-
textBox1.AppendText(text);
-
}
-
}
-
}
-
}
This code is ugly because :
- you need to create a delegate for each single public method you can call from outside
- you need to put an “if/else” block in each method wich increase the complexity of your code
The trick
Here is a trick that could significantly reduce the amount of code needed to do the same job within a large project.
Within you base class
You probably have a common base class for all your UI components. Add this method :
-
namespace TestWinForm
-
{
-
public class BaseForm : Form
-
{
-
// This allows a sub class to easily run a method within
-
// an UI thread without the need of creating multiple
-
// delegate signatures for each method signatures
-
protected virtual void ThreadSafe(MethodInvoker method)
-
{
-
if (InvokeRequired)
-
Invoke(method);
-
else
-
method();
-
}
-
}
-
}
Within your UI classes
Now the only thing you need to do is to encapsulate the methode content with the ThreadSafe() method :
-
namespace TestWinForm
-
{
-
public partial class MainForm : BaseForm
-
{
-
public MainForm()
-
{
-
InitializeComponent();
-
}
-
-
// public method that may be called from outside and within any
-
// worker thread …
-
public virtual void Display(string text)
-
{
-
ThreadSafe(delegate
-
{
-
//do any UI related code here
-
//note that because this is an anonym method,
-
//you can use the local parameter
-
textBox1.AppendText(text);
-
});
-
}
Happy coding !