Given the following classes
public class FirstFoo {
public string Bar { get; }
public string Baz { get; }
public FirstFoo(string bar, string baz)
{
Bar = bar;
Baz = baz;
}
}
public class SecondFoo {
public string Bar { get; }
public string Baz { get; }
public SecondFoo(string bar, string baz)
{
Bar = bar;
Baz = baz;
}
}
and the following mapping definition
Mapper.CreateMap<FirstFoo, SecondFoo>();
I would have expected Mapper.Map<SecondFoo>(firstFooInstance) to Just Work(TM), but it throws an ArgumentException
System.ArgumentException: Type 'SecondFoo' does not have a default constructor
Am I doing something wrong here?
Disclaimer: We're still using AutoMapper 2.2.1. I've perused the change log to figure out if this feature was introduced in a later release, but I've only found bugfixes or other improvement when searching for "constructor" in all entries, and 2.2.1 and earlier releases don't have any details in the change log, so I can't even confirm that it should work. (And yes, I'm aware this is a very old release. I'm looking at updating to the latest release across the large enterprise solution this is part of, but it's not a priority issue. It might become one, if it solves this issue, but I won't spend time on it just in case...)
Wow, this is a little embarassing. Apparently, the type I was mapping to had a property which the type I was mapping from didn't have, meaning that there was no way to fill all the constructor arguments. I was totally thrown off by the error message about there being no default constructor (had I mapped to mutable properties, AutoMapper would have complained about an invalid mapping and given me a hint on which property was missing...).
Update: I filed an issue with AutoMapper, and this will be fixed in the next release!
Related
I just stumbled upon something that's got me scratching my head. Using Visual Studio 2013 Update 3, I accidentally assigned a property an object without providing the new operator or a type and it compiled, but threw an exception upon execution.
Here's an example of what I was doing:
public class Outer
{
public Inner Inner { get; set; }
}
public class Inner
{
public bool Property { get; set; }
}
Instantiation of new Outer:
var outer = new Outer
{
Inner = {Property = true}
};
I would expect to see a compiler error in this case, but this is compiling successfully. So, is this a bug or some new feature I've stumbled upon that I'm just not using correctly?
I have several classes all implementing an interface IBar. Those classes are BarA, BarB, BarC.
I also have a base class Foo:
abstract class Foo
{
void Do(IBar bar)
{
Handle((dynamic)bar);
}
void Handle(IBar bar)
{
Console.Out.WriteLine("Fallback Scenario");
}
}
I want a child class FooChild like follows:
class FooChild : Foo
{
void Handle(BarA bar) {
Console.Out.WriteLine("Handling BarA");
}
void Handle(BarB bar) {
Console.Out.WriteLine("Handling Bar");
}
}
No I want to do the following, but I don't get the result I expect
var foo = new FooChild();
foo.Handle(new BarA()); // expected: Handling BarA, actual: Fallback Scenario
foo.Handle(new BarB()); // expected: Handling BarB, actual: Fallback Scenario
foo.Handle(new BarC()); // expected: Fallback Scenario, actual: Fallback Scenario
I can solve it by moving the Do(IBar bar) method to the FooChild class, but I don't want to do that. I might have 10 Foo childs and don't want to repeat that code. Is there a solution for this?
I think you want this:
void Do(IBar bar)
{
dynamic dynamicThis = this;
dynamicThis.Handle((dynamic) bar);
}
That way the method will be found against the actual type of this. Otherwise, the compiler remembers that the method was called from Foo, and only treats the argument dynamically, finding methods which would have been available from Foo with the actual type of bar. You want methods which would have been available from the actual type of this, as well as using the actual type of bar (via the cast to dynamic).
(You'll need to make the Handle methods public though.)
whats difference between Auto-Implemented Properties and manual properties in c#?
for Example:
Manual Properties:
private int uno;
public int Uno
{
get { return uno; }
set { uno = value; }
}
Auto Implemented Prop:
public string UserLeaveCount { get; set; }
i found the difference and uses here : Auto Implemented Prop
But Here is my Specific doubt thats "there is no instance variable in auto implemented properties and how is it stored,returned values?"
It's just syntactic sugar -- the compiler inserts the backing field for you. The effect is the same, except that, of course, there's no way for you to access the backing field from your code.
From the page you linked to:
When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
Suppose I have a List<IMyInterface>...
I have three classes which implement IMyInterface: MyClass1, MyClass2, and MyClass3
I have a readonly Dictionary:
private static readonly Dictionary<Type, Type> DeclarationTypes = new Dictionary<Type, Type>
{
{ typeof(MyClass1), typeof(FunnyClass1) },
{ typeof(MyClass2), typeof(FunnyClass2) },
{ typeof(MyClass3), typeof(FunnyClass3) },
};
I have another interface, IFunnyInteface<T> where T : IMyInterface
I have a method:
public static IFunnyInterface<T> ConvertToFunnyClass<T>(this T node) where T : IMyInterface
{
if (DeclarationTypes.ContainsKey(node.GetType())) {
IFunnyInterface<T> otherClassInstance = (FunnyInterface<T>) Activator.CreateInstance(DeclarationTypes[node.GetType()], node);
return otherClassInstance;
}
return null;
}
I'm trying to call the constructor of FunnyClasses and insert as parameter my MyClass object. I don't want to know which object it is: I just want to instantiate some FunnyClass with MyClass as a parameter.
What happens when I call ConvertToFunnyClass, T is of type IMyInterface, and when I try to cast it to FunnyInterface<T>, it says I can't convert FunnyClass1, for instance, to FunnyInterface<IMyInterface>
My current workaround (not a beautiful one), is this:
public static dynamic ConvertToFunnyClass<T>(this T node) where T : IMyInterface
{
if (DeclarationTypes.ContainsKey(node.GetType())) {
var otherClassInstance = (FunnyInterface<T>) Activator.CreateInstance(DeclarationTypes[node.GetType()], node);
return otherClassInstance;
}
return null;
}
And I don't like it because the return type is dynamic, so when I access it from somewhere else, I have no idea what type it is, and I lose intellisense, and stuff. I don't know about any performance implications either.
Any clues?
Thanks in Advance!
Resolution
As I'm using C# 4.0, I could stop casting errors using covariance (output positions only), and so I changed my IFunnyInterface to
IFunnyInteface<out T> where T : IMyInterface
Thank you all for the replies.
Essentially, your problem is that you are trying to convert FunnyInterface<T> to FunnyInterface<IMyInterface>. As has been mentioned several times (one example is here, more information here), this is not valid in most circumstances. Only in .NET 4, when the generic type is an interface or delegate, and the type parameter has been explicitly declared as variant with in or out, can you perform this conversion.
Is FunnyInterface actually an interface?
thecoop answer points you exactly to why you can't do it.
A cleaner solution to the problem (besides using dynamic) would be a base non-Generics Interface:
public interface IFunnyInterfaceBase
{
}
public interface IFunnyInteface<T> : IFunnyInterfaceBase
where T : IMyInterface
{
}
And you need to move methods signature you use in that code from IFunnyInteface to IFunnyInterfaceBase.
This way you would be able to write something like this:
MyClass2 c2 = new MyClass2();
IFunnyInterfaceBase funnyInstance = c2.ConvertToFunnyClass();
The Exception you said you got in your code is not due to the extension method signature itself (the method is fine)..it is originated by the type of your lvalue (the type of the variable you use to store its return value)!
Obviously this solution applies only if you can modify IFunnyInterface source code!
Today I had something weird happen in my copy of Resharper 5. I have a class that looks like this:
public class Foo
{
public string Username { get; private set; }
public Foo (string userName) { Username = userName; }
public void Bar()
{
DoWork(Username);
}
public void DoWork(string userName) { }
}
When I start to type DoWork(us I get the following from intellisense:
Notice that it's pulling up the constructor argument, and it ends with a colon: userName:
What's going on here?
EDIT:
As Reed answered below, this is a new C# 4 feature called Named and Optional Arguments. It's purpose is to allow you to specify the name of an argument, rather than it's position in a parameter list. so you don't have to remember the position of an argument in the argument list to use it (though this is largely meaningless with intellisense). It does make optional arguments easier to use though.
Thanks Reed.
This is Resharper providing intellisense support for Named and Optional Arugments.
C# 4 added support for these. You can now have a method defined like this:
public void DoWork(int someArgument = 3, string userName = "default")
{
// ...
If you want to call this with a different "userName" but leave the default for other parameters, you can do:
this.DoWork(userName: "FooUser");
Resharper 5 adds support for this syntax in intellisense.
You didn't include the ; at the end of userName
public Foo (string userName) { Username = userName; }