Posts Tagged ‘csharp’

How I write Equals and GetHashCode in csharp

April 25th, 2014

My code is copied with pride from the net.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
///
This is standard overridden Equals method.
/// Code is copied with pride from
/// http://msdn.microsoft.com/en-us/library/336aedhh(v=vs.85).aspx
///

//////
public override bool Equals(object obj)
{
if (null == obj || GetType() != obj.GetType())
{
return false;
}
var b = (MyType)obj;
return
this.Property1 == b.Property1 &&
...
this.PropertyN == b.PropertyN;
}

///
This is the ordinary overriden GetHashCode
/// with code proudly copied from
/// http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode
///

///
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
const int Salt = 23;
var hash = 17;
hash = hash + Salt * Property1.GetHashCode();
...
hash = hash + Salt * (null == PropertyN ? 0 : PropertyN.GetHashCode());  // Nullable values has to be taken care of.
return hash;
}
}

Unit testing private methods

March 25th, 2014

Read here instead.

I have a dirty but simple way to unit test private methods.

I create a wrapper method that I prefix with UT_ and write a comment that is only used for unit testing.
To be honest I haven’t done this on a public API but I wouldn’t hesitate for a public-within-a-company method.

1
2
3
4
5
6
7
8
9
10
11
12
</del>

<del>private int MyMethod( int myParameter ){</del>
<del> ComplexBusinessLogic...</del>
<del> }</del>

<del>///&lt;summary&gt;This helper method is only used for unit testing. Do Not call it in normal operations.&lt;/summary&gt;</del>
<del> internal int UT_MyMethod( int myParameter ){</del>
<del> return MyMethod( myParameter );</del>
<del> }</del>

<del>

I use InternalsVisibleTo to make internals visible to my unit testing project.

One can play with protected methods and inheritance too.

Tip when using DebuggerDisplay in Dotnet/Visual studio

March 7th, 2013

When debugging and watching an object one only sees the name of the type in the debugger.

1
MyProjectNamespace.Meeting

The quickest solution is to click the little plus sign or use the keyboard right arrow to show the properties. This is ok to do once or twice but doing this for every comparison is a waste of time at best.

Better then is to use SystemDiagnostics.DebuggerDisplay like so:

1
2
3
[DebuggerDisplay("ID:{ID}, UID:{UID}, Name:{Name}, Type:{this.GetType()}")]
public class Meeting : BaseClass {
...

to get

1
ID:1, UID:234abc, Name:XYZ, Type:MyProjectNamespace.Meeting

The Tip was to use {this.GetType()} in the argument of DebuggerDisplay.

Update

To show count of lists use something in the lines of:

1
[DebuggerDisplay("ID:{ID},Customers:{Customers==null?(int?)null:Customers.Count}")]

Update update

Since the DebuggerDisplay parameter is written as is into the assembly it might not work between languages. A solution for this is to call a method instead as most lanuguages uses the MyMethod() syntax.

It is also creates less overhead to call a method instead of having the expression in a string according to the MSDN link below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[DebuggerDisplay("{DebuggerDisplay(),nq}")]
public class ExchangeRateDto
{
public int ID { get; set; }

public string Name { get; set; }

#if DEBUG
private string DebuggerDisplay()
{
return
$"ID:{this.ID}, Name:{this.Name}, Type:{this.GetType()}";
}
}
#endif

Update update update

Use nameof. Also skip the this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[DebuggerDisplay("{DebuggerDisplay(),nq}")]
public class ExchangeRateDto
{
public int ID { get; set; }

public string Name { get; set; }

#if DEBUG
private string DebuggerDisplay()
{
return
$"{nameof(ID)}:{ID}, {nameof(Name)}:{Name}, Type:{GetType()}";
}
}
#endif

Update update update update

I have noticed that in Visual Studio 2022 (possibly earlier) one can ctrl-. on the class or record name and Visual studio writes the boilerplate code. The DebuggerDisplay is called GetDebuggerDisplay and only returns this.ToString() unfortunately. So it has to be adapted.

Praise where praise is due: https://blogs.msdn.microsoft.com/jaredpar/2011/03/18/debuggerdisplay-attribute-best-practices/.

There is more documentation at Stack overflow documentation.

Search Term: DebuggerDisplayAttribute

Visual studio snippet for an enhanced #region in csharp

March 2nd, 2013

Visual studio contains snippets.  These are “shortcuts” for writing various code.  Try writing for in the editor and text is typed in for you and you get placeholders for faster code writing.

One can write code like this oneself.  It is quite easy.  Just go to menu->Tools->Code snippets manager and work from there; copy, paste and rewrite to your will.  (The location field is the folder of the very snippets.)

Here is an example of mine.

I know that some people swear that #region is the devil’s own child but there are other, let’s call us them for pragmatists for now that say that if it fits it fits.  The standard snippet outcome for a region is

1
2
3
4
5
#region // Name of region.
//code
//code
//code
#endregion

but I prefer

1
2
3
4
5
#region // Name of region.
//code
//code
//code
#endregion // Name of region.

So I just copypasted the existing snippet to this; which you can import through above mentioned menu.<?xml version=”1.0″ encoding=”utf-8″ ?>

<CodeSnippets xmlns=”http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet”>
<CodeSnippet Format=”1.0.0″>
<Header>
<Title>#region</Title>
<Shortcut>region</Shortcut>
<Description>Code snippet for #region</Description>
<Author>Microsoft Corporation</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>name</ID>
<ToolTip>Region name</ToolTip>
<Default>MyRegion</Default>
</Literal>
</Declarations>
<Code Language=”csharp”><![CDATA[#region $name$
$selected$ $end$
#endregion // $name$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

Using using for abbreviating type aliases

February 29th, 2012

I have found a third use for C# using statement.

The first is for including namespaces, the second is shorthand for making use Dispose is called and the third is for naming types.

using Cache = Dictionary<string, KeyValuePair<string,string>();
Cache cache = new Cache();

As can be seen in the code above I have replaced a long type description with a short.

Honour thouse who should.