Showing posts with label Generic Constraints. Show all posts
Showing posts with label Generic Constraints. Show all posts

Saturday, August 15, 2015

Create objects from default constructor

Do you think that title sound redundant? If so, which method were you thinking of? Because there are several! Let's talk about those...and be sure to scroll to the bottom for a performance comparison!

Sample Class

Here is the class that we will be instantiating in our tests.

internal class TestClass
{
 public Guid Guid { get; private set; }
 
 public TestClass()
 {
 Guid = Guid.NewGuid();
 }
}

The new Keyword

This is the obviously, easier, fastest, normal way of instantiating an object...obviously.

[Fact]
public void NewDuh()
{
 var testObject = new TestClass();
 Assert.NotNull(testObject.Guid);
}

Activator.CreateInstance

This is a very simple and common way to instantiate an object from a Type object. It has an overload that takes a params object collection to let you use other, non default, constructors.

[Fact]
public void ActivatorCreateInstance()
{
 var type = typeof (TestClass);
 var instance = Activator.CreateInstance(type);
 var testObject = Assert.IsType<TestClass>(instance);
 Assert.NotNull(testObject.Guid);
}

Saturday, May 30, 2015

.NET Generic Overloads: How to support T and IList

What happens when you want to overload a generic method where the first method accepts a single object and the other accepts an IList of that type?

It will only work when specifically try to pass in an IList. If you try to pass in a List it will fail because the compiler will identify the generic parameter overload and fail before trying to use the implicit cast to an IList.

This is because a C# compiler tries to identify overloaded methods it checks for matching parameters in the following order:

  1. Explicit type matches.
  2. Generic parameters.
  3. Implicit type matches.

Let's look at an example!

Example of what DOES NOT work.

public class OverloadSample1
{
 [Fact]
 public void Test()
 {
 // Matches Method A - Good
 ISample sample = new Sample();
 this.Method(sample);
 
 // Matches Method B - Good
 IList<ISample> samples1 = new List<ISample>();
 this.Method(samples1);
 
 // Matches Method A - BAD!
 List<ISample> samples2 = new List<ISample>();
 this.Method(samples2);
 }
 
 // A
 public void Method<T>(T sample)
 where T : ISample
 {
 }
 
 // B
 public void Method<T>(IList<T> sample)
 where T : ISample
 {
 }
}

...so, how do we solve this problem?

Subscribe to: Posts (Atom)

AltStyle によって変換されたページ (->オリジナル) /