Why is generated override code for generic method incorrect? - visual-studio-2010

I have an abstract generic class
public abstract class Foo<TType>
with an abstract method
public abstract object DoSomething(TType arg = default(TType)) {}
Now, the inherited class
public class BabyFoo : Foo<string>
when I want to override DoSomething and start typing "override " to get the intellisense/generator to write a method skeleton I expected
public override object DoSomething(string arg = default(string))
or even
public override object DoSomething(string arg = null)
but it literally comes up with
public override object DoSomething(string arg = default(TType))
My initial thought is it is a VS2010 bug since optional params are new to c#, but can anybody tell me if there is perhaps a real reason why (reference types vs value types??) the IDE generates this code?

Just to clarify:
public abstract class Foo<TType>
{
public abstract object DoSomething(TType arg = default(TType));
}
public class BabyFoo : Foo<string>
{
// Expected:
public override object DoSomething(string arg = default(string))
// Actual:
public override object DoSomething(string arg = default(TType));
}
Unless there's something I'm missing, it's quite simply a bug in the Visual Studio IDE / code-gen. Changing the method signature to the "expected" one results in code that will compile, as the "actual" one refuses to compile thanks to being clearly invalid.
Having tried a few different types for TType as well as things like the where TType : new() constraint, I couldn't get VS to generate valid code with your DoSomething method.
Congratulations - you've (probably) found a bug in Visual Studio =)
There are always edge cases when it comes to code generation, I logged one for Visual Basic 2005/2008 a long time ago that was resolved WONT FIX as it was a really obscure one comparatively. Hopefully this one'll be fixed though!

Related

C# Attribute or Code Inspection Comment to Encourage or Discourage Call to Base Method from Virtual Method Override

I'm working on a C# project in Unity with Rider.
I sometimes see a base class with an empty virtual method, and then a derived class that overrides that method. The method override has an explicit call to base.MethodName() even though the base method is empty.
public class A
{
public virtual void Method1() { }
public virtual void Method2()
{
// Important logic performed here!
}
}
public class B : A
{
public override void Method1()
{
base.Method();
// Do something else ...
}
public override void Method2()
{
// Do something here ...
}
}
When looking at the method in Rider's IL Viewer, the call to the base method is included, even though the method is empty.
Are there any method attributes or code inspection comments in C# or Rider that could:
Generate a compiler or code inspection warning when calling a base method that is empty.
Generate a compiler or code inspection warning when not calling a base method that is not empty.
For example:
public class A
{
[OmitCallFromOverride]
public virtual void Method1() { }
[RequireCallFromOverride]
public virtual void Method2()
{
// Important logic performed here!
}
}
I can imagine a scenario where multiple derived classes override a method and one or more mistakenly failed to call the base method, which might result in unexpected behavior. Or situations where there are unnecessary calls to an empty base method, which may be wasteful, but unlikely to break anything.
While I'm primarily inquiring about whether such attributes or code inspection comments exist, I am also curious to know of how people might handle these situations, such as simply always calling the base method from an override, keeping important logic out of base virtual methods, or using some other method of communicating whether a base method call is unnecessary or required.
Generate a compiler or code inspection warning when calling a base
method that is empty.
In c#, as far as I know, there is no warning for an empty method. So, I think there is no warning when calling a base method that is empty.
But you are free to write one for you: Write your first analyzer and code fix
Generate a compiler or code inspection warning when not calling a base
method that is not empty.
Not in C#, and I think is not a good idea to force a derived class to call a base method. I can understand that in your scenario, it would be great if all your derived classes method call always the base method, but it will be a very uncommon case. And generally when we need tricky (not intuitive) rules, that means our solution is not very clear, or it will be error-prone.
keeping important logic out of base virtual methods
If you need A.Method1 to be called, maybe let it as a virtual method is not a good idea. You have a virtual method when you want to give to your derived classes the opportunity to use it OR to overwrite it with a more adapted version.
I propose you a solution that maybe you can adapt to your scenario.
abstract class A
{
public abstract void Method1();
public virtual void Method2() { }
public void MustBeCalled()
{
// Here you can put the logic you had in Method1, you need to execute this code, so this method can't be overwrited.
}
public void TemplateMethod()
{
Method1();
MustBeCalled();
// Do something else ...
}
}

Inheriting default methods with the same name in the class without any compilation error

How a class can implement two interfaces with the same default method in Java 8.
I was not able to get the concept behind the same default method from different interfaces getting inherited in the sub class.Please explain the issue.
interface House {
default String getAddress() {
return "101 Main Str";
}
}
interface Bungalow extends House {
default String getAddress() {
return "101 Smart Str";
}
}
class MyHouse implements Bungalow, House {
}
public class TestClass {
public static void main(String[] args) {
House ci = new MyHouse(); //1
System.out.println(ci.getAddress()); //2
}
}
In the above code default method getAddress() in interface House is present.another method with the same name is declared as default in the extending interface Bungalow
How class MyHouse can implement both the interfaces without any compilation error(because it doesn't know which method has the preference in that case implementing should fail.)
If i call new MyHouse().getAddress(); gives compile error but it should give compilation error even without method calling from MyHouse class.
It seems that the answer is here, where there is a different example, but sort of makes sense and is really close to yours.
Ask me the exact same thing in 1/2 a year and I'll say it will fail at compile time and point me to this answer, so that I could read the JLS again. I guess this is how they decided to implement it. Without thinking too much, I, personally (may be wrong) think that this is at least counter intuitive...

why does this kill vs 2010

If you copy this into VS2010 it sobs and dies. Why?
A colleague sent this to me in a mail saying that this is why the dynamic keyword is dangerous and warning that it'd kill VS, I copied it into what I was working on and lo and behold, VS2010 crashed.(Destroying most of what I'd worked on that morning).
Warning , it'll kill VS without compiling or any other input, if it's there VS will crash.
namespace Crash
{
public class Foo
{
public static void Method(object o)
{
}
}
public class Bar
{
public Foo Foo { get; set; }
public static void Method(dynamic d)
{
Foo.Method(d); //This crashes VS instantly!
}
}
}
Someone has already logged a bug for this.
http://connect.microsoft.com/VisualStudio/feedback/details/704397/vs-crash-when-passing-dynamic-val-to-static-member-of-class-from-a-static-method-in-c
Conditions necessary to cause the crash:
The static method being called must be referenced via only the class name (i.e. without a namespace).
The method making the call must also be static, and the class it belongs to must have a non-static property with the same name as the class whose method is being called.
The dynamic value being passed to it can come from anywhere - it doesn't have to be an argument to the calling function as in the example.

C# Function Inheritance--Use Child Class Vars with Base Class Function

Good day, I have a fairly simple question to experienced C# programmers. Basically, I would like to have an abstract base class that contains a function that relies on the values of child classes. I have tried code similar to the following, but the compiler complains that SomeVariable is null when SomeFunction() attempts to use it.
Base class:
public abstract class BaseClass
{
protected virtual SomeType SomeVariable;
public BaseClass()
{
this.SomeFunction();
}
protected void SomeFunction()
{
//DO SOMETHING WITH SomeVariable
}
}
A child class:
public class ChildClass:BaseClass
{
protected override SomeType SomeVariable=SomeValue;
}
Now I would expect that when I do:
ChildClass CC=new ChildClass();
A new instance of ChildClass should be made and CC would run its inherited SomeFunction using SomeValue. However, this is not what happens. The compiler complains that SomeVariable is null in BaseClass. Is what I want to do even possible in C#? I have used other managed languages that allow me to do such things, so I certain I am just making a simple mistake here.
Any help is greatly appreciated, thank you.
You got it almost right, but you need to use properties instead of variables:
public abstract class BaseClass {
protected SomeType SomeProperty {get; set}
public BaseClass() {
// You cannot call this.SomeFunction() here: the property is not initialized yet
}
protected void SomeFunction() {
//DO SOMETHING WITH SomeProperty
}
}
public class ChildClass:BaseClass {
public ChildClass() {
SomeProperty=SomeValue;
}
}
You cannot use FomeFunction in the constructor because SomeProperty has not been initialized by the derived class. Outside of constructor it's fine, though. In general, accessing virtual members in the constructor should be considered suspicious.
If you must pass values from derived classes to base class constructor, it's best to do it explicitly through parameters of a protected constructor.

RhinoMocks: Correct way to mock property getter

I'm new to RhinoMocks, and trying to get a grasp on the syntax in addition to what is happening under the hood.
I have a user object, we'll call it User, which has a property called IsAdministrator. The value for IsAdministrator is evaluated via another class that checks the User's security permissions, and returns either true or false based on those permissions. I'm trying to mock this User class, and fake the return value for IsAdministrator in order to isolate some Unit Tests.
This is what I'm doing so far:
public void CreateSomethingIfUserHasAdminPermissions()
{
User user = _mocks.StrictMock<User>();
SetupResult.For(user.IsAdministrator).Return(true);
// do something with my User object
}
Now, I'm expecting that Rhino is going to 'fake' the call to the property getter, and just return true to me. Is this incorrect? Currently I'm getting an exception because of dependencies in the IsAdministrator property.
Can someone explain how I can achieve my goal here?
One quick note before I jump into this. Typically you want to avoid the use of a "Strict" mock because it makes for a brittle test. A strict mock will throw an exception if anything occurs that you do not explicitly tell Rhino will happen. Also I think you may be misunderstanding exactly what Rhino is doing when you make a call to create a mock. Think of it as a custom Object that has either been derived from, or implements the System.Type you defined. If you did it yourself it would look like this:
public class FakeUserType: User
{
//overriding code here
}
Since IsAdministrator is probably just a public property on the User type you can't override it in the inheriting type.
As far as your question is concerned there are multiple ways you could handle this. You could implement IsAdministrator as a virtual property on your user class as aaronjensen mentioned as follows:
public class User
{
public virtual Boolean IsAdministrator { get; set; }
}
This is an ok approach, but only if you plan on inheriting from your User class. Also if you wan't to fake other members on this class they would also have to be virtual, which is probably not the desired behavior.
Another way to accomplish this is through the use of interfaces. If it is truly the User class you are wanting to Mock then I would extract an interface from it. Your above example would look something like this:
public interface IUser
{
Boolean IsAdministrator { get; }
}
public class User : IUser
{
private UserSecurity _userSecurity = new UserSecurity();
public Boolean IsAdministrator
{
get { return _userSecurity.HasAccess("AdminPermissions"); }
}
}
public void CreateSomethingIfUserHasAdminPermissions()
{
IUser user = _mocks.StrictMock<IUser>();
SetupResult.For(user.IsAdministrator).Return(true);
// do something with my User object
}
You can get fancier if you want by using dependency injection and IOC but the basic principle is the same across the board. Typically you want your classes to depend on interfaces rather than concrete implementations anyway.
I hope this helps. I have been using RhinoMocks for a long time on a major project now so don't hesitate to ask me questions about TDD and mocking.
Make sure IsAdministrator is virtual.
Also, be sure you call _mocks.ReplayAll()
_mocks.ReplayAll() will do nothing. It is just because you use SetupResult.For() that does not count. Use Expect.Call() to be sure that your code do everything correct.

Resources