I'm trying to do some unit testing on a project that unfortunately has high level of unit interdependence. Currently, a lot of our classes look to a custom UserIdentity object to determine authentication, but that object has a lot of internal hoop-jumping that I would just as soon avoid when trying to test individual unit functionality.
To work around some of this, I'm trying to create a "mock" version of this UserIdentity that can be plugged in with a more tightly-controlled variable environment.
Long story short, we have a UserIdentity class with several public read-only properties and a static CurrentIdentity (IIdentity) placeholder. I'm able work around just about everything with a "mock" IIdentity implementation, but I'm running into a wall when I reach a point where the CurrentIdentity is cast as a UserIdentity.
It's a pretty straight-forward method:
internal static UserIdentity GetCurrentIdentity()
{
UserIdentity currentIdentity = ApplicationContext.User.Identity as UserIdentity;
return currentIdentity;
}
I've set up my mock object to create a member of the UserIdentity type, and then do something like this:
public static implicit operator UserIdentity(MockUserIdentity src)
{
return src.UserIdentity;
}
or this
public static explicit operator UserIdentity(MockUserIdentity src)
{
return src.UserIdentity;
}
The problem is that as far as I can tell, that 'as' doesn't seem to invoke either an implicit or explicit conversion operation on my mock object. My question(s) is(are?), am I missing something simple here or will this not work because (I'm guessing) the 'as' operation looks directly to class inheritance (which my object does not do...)?
Also, a bit off topic maybe, but why can there not be simultaneous explicit and implicit operators of the same resultant type within a class? Unless I'm missing something silly, the compiler balks if I try to have both conversion operators at once. I have to pick one or the other.
UPDATE
Okay, now I'm thoroughly confused. Maybe I'm getting sloppy, but I've tried doing the direct cast, and I can't seem to get that to work either. I read up on the operator at MSDN, and the example shows the operator going in the resultant class rather than the source class, but I'm not sure if that matters or not (I tried both places in the code below). Either way, I tried to set up a simple test bed to see what I might be doing wrong, but I can't get that to work either...Here's what I've got
class Program
{
// Shared Interface
public interface IIdentity { }
// "real" class (not conducive to inheritence)
public class CoreIdentity : IIdentity
{
internal CoreIdentity() { }
// Just in case (if this has to be here, that seems unfortunate)
public static explicit operator CoreIdentity(ExtendedIdentity src)
{
return src.Identity;
}
}
// "mock" class (Wraps core object)
public class ExtendedIdentity : IIdentity
{
public CoreIdentity Identity { get; set; }
public ExtendedIdentity()
{
Identity = new CoreIdentity();
}
// This is where the operator seems like it should belong...
public static explicit operator CoreIdentity(ExtendedIdentity src)
{
return src.Identity;
}
}
// Dummy class to obtain "current core identity"
public class Foo
{
public IIdentity Identity { get; set; }
public CoreIdentity GetCoreIdentity()
{
return (CoreIdentity)Identity;
}
}
static void Main(string[] args)
{
ExtendedIdentity identity = new ExtendedIdentity();
Foo foo = new Foo();
foo.Identity = identity;
CoreIdentity core = foo.GetCoreIdentity();
}
}
But that throws the following exception when I invoke foo.GetCoreIdentity():
Unable to cast object of type 'ExtendedIdentity' to type 'CoreIdentity'.
and I can't catch either of my explicit operators with a break point, so it looks like it's making this determination without even "trying" the conversion routes I've provided.
Surely I'm missing something obvious. Does the fact that I have my Identity (in Foo) defined as IIdentity somehow prevent resolution of the cast using the explicit operators of the implementing type? That would strike me as odd.
UPDATE (#2)
I feel like I'm spamming my post with all these updates (maybe I should get my act together before being so trigger-happy :) ) Anyway, I modified my Foo's GetCoreIdentityMethod to do this instead:
public CoreIdentity GetCoreIdentity()
{
ExtendedIdentity exId = Identity as ExtendedIdentity;
if (exId != null)
return (CoreIdentity)exId;
return (CoreIdentity)Identity;
}
and (after having to clean up the ambiguous reference caused by having the operator in both classes), it did step into my explicit conversion operator code, and it did work as expected. So I guess it looks like the explicit operators are not resolved polymorphically (is that the correct understanding?), and the fact that my property was typed as an IIdentity rather than an ExtendedIdentity prevented it from invoking the cast logic even though it was of the ExtendedIdentity type at the time it was invoked. That strikes me as very peculiar and unexpected....and kind of unfortunate.
I don't want to have to re-write the keeper of the CurrentIdentity object to make it aware of my special test cast mocks. I wanted to encapsulate that "special" logic into the mock itself, so this really throws me for a loop.
Does the fact that I have my Identity
(in Foo) defined as IIdentity somehow
prevent resolution of the cast using
the explicit operators of the
implementing type?
Here's a hint: how do you define an explicit (or implicit, for that matter) conversion operator? (I know you know this since you already did it; I am asking the question to illustrate a point.)
public static explicit operator UserIdentity(MockUserIdentity src)
{
return src.UserIdentity;
}
There's something very important to realize here. The C# designers made the wise choice of making all operators static. So the explicit operator defined above translates to essentially a static method call looking something like this:
public static UserIdentity op_Explicit(MockUserIdentity src)
{
return src.UserIdentity;
}
Now, here is what I'm getting at. The behavior that perplexed you in your question because it seemed to fail in the polymorphism department was really the result of C#'s system of method overload resolution.
If I have two methods:
void Write(string s) { Console.WriteLine("string"); }
void Write(object o) { Console.WriteLine("object"); }
...and then I have this program:
object x = "Hello!";
Write(x);
What will the output be?
The answer is "object" because the Write(object) overload was selected by the compiler -- as well it should have been. Write is not an instance method to be overridden by some derived type according to normal polymorphism; it is a static method, with overloads between which the compiler must make a choice. Since x in the above code is declared to be of type object, that choice is unambiguously Write(object).
So in the case of your code, where you have this:
public IIdentity Identity { get; set; }
public CoreIdentity GetCoreIdentity()
{
return (CoreIdentity)Identity;
}
The compiler must investigate: is there an op_Explicit overload which accepts an IIdentity parameter? No, there is not. There's one that accepts a UserIdentity parameter, but that's too specific (just as Write(string) was too specific for x in the example above).
So the reason your explicit operator was not called in your initial tests was that the compiler will not resolve (CoreIdentity)Identity to that particular overload. This is also why your modified version does work:
public CoreIdentity GetCoreIdentity()
{
ExtendedIdentity exId = Identity as ExtendedIdentity;
if (exId != null)
{
// Since exId is actually declared to be of type ExtendedIdentity,
// the compiler can choose the operator overload accepting
// an ExtendedIdentity parameter -- so this will work.
return (CoreIdentity)exId;
}
return (CoreIdentity)Identity;
}
as does not invoke conversion operators. See: http://msdn.microsoft.com/en-us/library/cscsdfbt(v=VS.100).aspx
Use a (cast).
So, why don't you use an explicit cast?
// will throw if cast fails
internal static UserIdentity GetCurrentIdentity()
{
UserIdentity currentIdentity = (UserIdentity) ApplicationContext.User.Identity ;
return currentIdentity;
}
This ought to trigger your explicit operator. You can test with is first to make it safer.
As mentioned by Ray as doesn't invoke the conversion operators.
That said, you should be using an explicit cast in that type of scenarios.
That way, You get very clear information when something isn't set up right and the object at ApplicationContext.User.Identity wasn't what the code expected it to.
Related
As question asked Here 8 years ago but I think there should be a way(New Patterns , New Designs , New Architectures or anything else.) to enforce method don't return null.
As you know there are some implications with returning null in a method one important for me is:
Handling null in Consuming-Side and understandable semantics like:
Method:
public ClassName Do()
{
...
return null;
}
And calling Do() like (Attention Comments also):
var objVal = Do();
//Accessing property of ClassName raised exception
var pnVal = objVal.PropName;//Exception id objVal is null
//But I should handle if it is not null then do anything I want
if(objVal!= null)
{
//Do something
}
after many problem on product by above way I came to this conclusion to generalize all method to follow a pattern to be readable,clean and preventing ambiguous semantic.
so a very basic Way is using Struct type because structure can't be null , if a return type of methods be structure then they can't return null and We know this in compile time not in runtime.
So I implement that above method like:
1- Make DTO out and in for method, in this case just out:
public struct Do_DTO_Out
{
public ClassName Prop1 { get; set; }
public bool IsEmpty
{
get
{
return Prop1 == null;
}
}
public static Do_DTO_Out Empty
{
get
{
return new Do_DTO_Out() { Prop1 = null };
}
}
}
2- And Do method should be:
public Do_DTO_Out Do()
{
try
{
return manipulatedObj;
}
catch (Exception exp)
{
}
return Do_DTO_Out.Empty;
}
3- In consuming side:
var objVal = Do();
if (!objVal.IsEmpty)
//Do something
Is struct is best way ? is it worth to change all method and create DTO in and out for each of them (I think so).
Is there better way to do that , any idea,help,answer would be truly appreciated.
Your 'reference type' to 'struct with property check' conversion seems useless to me. It also requires intimate knowledge of your intention, while the reference type null check is very obvious to anyone reading it later.
I think code contracts could work for you. It provides you with compile time static analysis and runtime checks. Just make sure you have the appropriate contract as post condition:
public ClassName Do()
{
...
object returnValue = null;
Contract.Ensures(returnValue != null);
return returnValue;
}
Assuming that value can never be null otherwise the if is unavoidable (but for a single method call you can now write Do()?.DoSomething()).
If you can introduce code contracts (see Patrick's answer) then I completely agree with Patrick and you should go with them. If it's not viable (because your codebase is already too big or you're targeting an environment where they aren't supported) then I'd first use assertions:
var obj = Do();
Debug.Assert(obj != null);
// Use obj...
We're however moving this responsibility to calling point and it may be tedious. If you want to make this interface explicit then you can use something a struct as you thought but throwing an exception at calling point (where the error is):
public NotNullable<SomeClass> Do() { }
Where NotNullable<T> is defined as:
public struct NotNullable<T> where T : class
{
public NotNullable(T value)
{
Value = value ?? throw new ArgumentNullException(nameof(value));
}
public T Value { get; }
}
However I do not like to explicitly access .Value at calling point then I'd make it transparent adding:
public static implicit operator T(NotNullable<T> rhs)
=> rhs.Value;
Now caller can be:
MyClass obj = Do();
obj.DoSomthing();
And the proper exception is thrown (at run-time, unfortunately) when object is created. Playing with [Conditional("DEBUG")] you may exclude that check for release builds having then a behavior similar to Debug.Assert() and a minimal (but still present) overhead.
Note that this makes sense only if you want to document interface method about this constraint directly in its signature. If you're not interested in this then keep it as simple as possible:
public SomeClass Do()
{
MyClass somevalue = ...
// ...
return NotNull(somevalue);
}
Where NotNull() is a static method define somewhere and imported with using static or even an extension method for object called as return somevalue.NotNull().
I don't especially like this approach because I think Debug.Assert() is enough in these cases but it's just my opinion. Of course maybe someday we will have Nullable Reference Types in C# then we'll get compile-time enforcement (as object? or the other way round object!).
Returning null is a bad practice - better to implement
NullObject Design Pattern
I have a class that overrides the addition operator twice. One that takes the type parameter and one that takes a double:
public class A<T>
{
public A() { }
public static A<T> operator +(A<T> a, T t)
{
Console.WriteLine("Generic add called.");
return new A<T>(); // return to keep the compiler happy
}
public static A<T> operator +(A<T> a, double d)
{
Console.WriteLine("Double add called.");
return new A<T>(); // return to keep the compiler happy
}
}
When the class is parameterized by the int type, it behaves as expected:
A<int> aInt = new A<int>();
var test = aInt + 3;
// -> Generic add called.
test = aInt + 3.0;
// -> Double add called.
But when parameterized by the double type, the non-generic add is called:
A<double> aDouble = new A<double>();
var otherTest = aDouble + 3.0;
// -> Double add called.
Assuming this behavior is the norm, I know which will be called. The non-generic override will be preferred. That said...
Will the non-generic method be always be preferred in the event of a collision?
All of the above code is available, runnable in your browser, here
EDIT: This question is related, but it's asking about generic methods, not classes. He gives this code:
class A
{
public static void MyMethod<T>(T myVal) { }
public static void MyMethod(int myVal) { }
}
which does not apply to my usage examples. Distinguishing between a.MyMethod(3) and a.MyMethod<int>(3) is obvious - one is generic and one is not.
The more specific method will be chosen, but that construction is a bad idea because it is technically unspecified behaviour.
To quote #EricLippert, substituting the code snippets for the ones from my question:
But the situation with [aDouble + 3.0] is far worse. The CLR rules make this sort of situation "implementation defined behaviour" and therefore any old thing can happen. Technically, the CLR could refuse to verify a program that constructs type [A<double>]. Or it could crash. In point of fact it does neither; it does the best it can with the bad situation.
Are there any examples of this sort of type construction causing truly implementation-defined behaviour?
Yes. See these articles for details:
http://blogs.msdn.com/b/ericlippert/archive/2006/04/05/odious-ambiguous-overloads-part-one.aspx
http://blogs.msdn.com/b/ericlippert/archive/2006/04/06/odious-ambiguous-overloads-part-two.aspx
Simple answering yes. The compiler assume that because you have treated by hand a particular type parameter, that means that it has some special logic for you. That's why the second operator is called. To say further, operators are nothing more than static methods that accepts some parameters. For your case it's a binary operator so the static method has two parameters.
My question is a bit similar to this one: How to convert an action to a defined delegate of the same signature?
Why there is no implicit convertion between delegates with same signature. For example, code:
class Program
{
private delegate void Foo1(int x);
private delegate void Foo2(int x);
static void Main(string[] args)
{
Foo1 foo1 = Console.WriteLine;
Foo2 foo2 = Console.WriteLine;
Call(foo1);
Call2(foo2);
}
static void Call(Action<int> action)
{
action(10);
}
static void Call2(Foo1 action)
{
action(10);
}
}
it does not compile because there isn't implicit convertion from Action<int> to Foo1.
But normaly it's the same thing. So it mean this names are aliases, not actualy names. So i think it was great idea to think about it like aliases. So in this case we have 3 aliases of a delegate, that get one int value and returns nothing. And this delegates are fully interchangeable one by another. But we don't have it. So question is: why? By signatures it's the same thing, and there isn't any implementation, so delegates with same signature are one and same with many aliases...
Is it C# defect or there are reasons for it? As to me, i don't see any.
There's no implicit conversion between those two delegates for the same reason that there's no implicit conversion between these two types:
public sealed class Foo1
{
public string Value { get; set; }
}
public sealed class Foo2
{
public string Value { get; set; }
}
Just because two classes have the same fields doesn't mean that you should be able to treat one as if it were another. The same logic applies to delegates (which are also types, mind you).
There is semantic meaning applied to the creation of that type. If someone created a Foo1 they want it to be a Foo1, not a Foo2. If they're going out of their way to use a Foo1 where a Foo2 is expected, it's a big red flag that even though the types appear similar, there is a semantic difference between these two types. If the programmer knows something that the compiler doesn't, they can use an explicit conversion of some sort to indicate that they know what they're doing.
(The previous paragraph was intentionally written to apply equally to your delegates, and the classes I provided above.)
I'm trying to call an extension method on my own class, but it fails to compile. Consider the following lines of code:
public interface IHelloWorld
{
}
public static class Extensions
{
public static string HelloWorld(this IHelloWorld ext)
{
return "Hello world!";
}
}
public class Test : IHelloWorld
{
public string SaySomething()
{
return HelloWorld();
}
}
Basically I'm extending on the interface. I keep getting this error:
The name 'HelloWorld' does not exist in the current context
Can anybody explains this to me? When I do a cast all seems well:
return ((Test)this).HelloWorld();
Any explanations?
The cast isn't necessary - the this part is. So this works fine:
return this.HelloWorld();
Section 7.6.5.2 explicitly talks about method invocations of the form
expr.identifier ( )
expr.identifier ( args )
expr.identifier < typeargs > ( )
expr.identifier < typeargs > ( args )
This invocation:
HelloWorld()
isn't of that form, as there's no expression involved.
It's not immediately clear to me why the language was designed that way (i.e. why the "implicit this" was excluded) and maybe Eric Lippert will add an answer to that effect later. (The answer may well be along the lines of "because it would have taken a long time to spec, implement and test, for relatively little benefit.") However, this answer at least shows that the C# compiler is sticking to the spec...
this.HelloWorld(); works with no casting.
Remember how Extension methods work:
You use an object and compiler would know the type then it could resolve it to the extension method. If no object is used, then it would not be able to resolve it.
Not really an answer, but too long to fit in the comment section...
Let's take the following example, that I think is pretty common:
public class DoubleSet : List<double>
{
public IEnumerable<double> Square()
{
return this.Select( x => x*x );
}
}
It is a perfectly valid point that the this is not necessary for the compiler to interpret the Select method properly.
However I think that in some ways, imposing the dot notation highlights the fact that we're dealing with an extension method, and that as such, the extension method will only access the members of the current instance through public accessors, even if you're calling it within the private scope of the class.
It makes explicit to the code reader that the extension method will treat the "this" instance as if it didn't know anything of its internal state. And indeed the class of the object is completely unknown to the extension method (as the extension method only knows the interface)
If the code was only:
public IEnumerable<double> Square()
{
return Select( x => x*x );
}
it would be much less obvious that you're dealing with IEnumerable.Select that is actually calling the IList.GetEnumerator and getting every element one by one to call the x => x*x function.
I'm reading about extension methods, and monkeying around with them
to see how they work, and I tried this:
namespace clunk {
public static class oog {
public static int doubleMe(this int x) {
return 2 * x;
}
}
class Program {
static void Main() {
Console.WriteLine(5.doubleMe());
}
}
}
and it worked as expected, successfully extending int with the doubleMe method, printing 10.
Next, being an old C guy, I wondered if I could do this:
namespace clunk {
public static class BoolLikeC {
public static bool operator true(this int i) { return i != 0; }
public static bool operator false(this int i) { return i == 0; }
}
class Program {
static void Main() {
if ( 7 ) {
Console.WriteLine("7 is so true");
}
}
}
}
I would think if the former would work, then the latter ought to work to make it such that
an int used in a boolean context would call the extension method on int, check to see that
7 is not equal to 0, and return true. But instead, the compiler doesn't even like the
later code, and puts the red squiggly lines under the two this's and says "Type expected".
Why shouldn't this work?
Very clever! A nice attempt, but regrettably we did not implement "extension everything", just extension methods.
We considered implementing extension properties, extension operators, extension events, extension constructors, extension interfaces, you name it, but most of them were not compelling enough to make it into C# 4 or the upcoming version of C#. We got as far as designing a syntax for the sort of thing you mention. We got rather farther on extension properties; we almost got extension properties into C# 4 but it ended up not working out. The sad story is here.
http://blogs.msdn.com/b/ericlippert/archive/2009/10/05/why-no-extension-properties.aspx
So, long story short, no such feature, but we'll consider it for hypothetical future releases of the language.
You can of course make a "ToBool()" extension method on int if you really do like the retro C convention that non-zero-means-true.
Extension methods are exactly that—methods.
You cannot make extension operators or properties.
Had that been possible, it would result in very hard-to-read code.
If you aren't familiar with the code base, it's almost impossible to figure out what if (7) means.
As others have said, there's no such thing as extension operators in C#.
The closest you can get, running the risk of facilitating lots of nasty bugs down the line, would be with implicit conversion operators on a custom "bridge" type:
// this works
BoolLikeC evil = 7;
if (evil) Console.WriteLine("7 is so true");
// and this works too
if ((BoolLikeC)7) Console.WriteLine("7 is so true");
// but this still won't work, thankfully
if (7) Console.WriteLine("7 is so true");
// and neither will this
if ((bool)7) Console.WriteLine("7 is so true");
// ...
public struct BoolLikeC
{
private readonly int _value;
public int Value { get { return _value; } }
public BoolLikeC(int value)
{
_value = value;
}
public static implicit operator bool(BoolLikeC x)
{
return (x.Value != 0);
}
public static implicit operator BoolLikeC(int x)
{
return new BoolLikeC(x);
}
}
Unfortunately you cannot introduce new operators, or implement support for existing operators, on types, through extension methods.
Basically, what you want to do cannot be done.
The only way to introduce new operators is to put them in one of the involved types. For binary operators you can put them in your own type, provided your type is one of the two, for unary types you need to put the operator inside the type itself.
Since you can't extend an int in any way, you can't do it.
Console.WriteLine(5.doubleMe());
is equivalent to
Console.WriteLine(oog.doubleMe(5));
Given that, you can see why if ( 7 ) doesn't work.
Extension methods are nothing more than syntax.
As a side note since it is syntax you can call extension methods on null variables because it translates to a normal method call, and methods can take null parameters.
Unfortunately you cannot use extension methods to add operators, and implicit type conversion in C# is implemented as an operator.
In the first instance you are writing an extension method - e.g. extending the functionality of the int data type. In the second code set, you are trying to override the bool operators. These are two totally different things.