Simple question: Should I be bothered by...



  •  ...this C# code:

     

    var showComment = false;

     

    It annoys me. Especially as it's code that I have produced that gets changed.

    Please can someone give me a reason why this is good practise? I don't think anyone can but if you can that would be helpful as I shall bring this (and other) cases up in my appraisal.

     

    My thoughts are 'var'  should only be used where neccesary OR when Class-names are really long and it aids readabilit eg.

    ReallyLongClassName reallyLongClassName = new ReallyLongClassName();

    would become:

     var reallyLongClassName = new ReallyLongClassName()

    ...and even then, it's pushing it.

     



  •  I'm not sure what the var keyword is doing in C#, but then again, I think the pattern:

    ClassName instanceName = new ClassName()

    is equally fucked.

     

    So, no, it doesn't look too good to me (and I'm a javascript afficionado), but then again, the time spent on these posts might have been better spent on useful code, so let's not get lost in useless details.



  • On the same line you can clearly see what the type is and when you see the showComment variable somewhere else you can just hover over it and also see that it's a boolean. I have no problem with this.



    If you want to be absolutely sure what the type is then you can use the following:

    global::System.Boolean showComment = false;

    Because not everyone knows that bool is actually Boolean, and that it's in the System namespace, and you could have a subnamespace System so you will need to use the global alias.



  • "the time spent on these posts might have been better spent on useful code, so let's not get lost in useless details."

     

    I thought the point of this forum/site was to debate, amongst other things, good/bad coding-practise?

     



  • @miner49er said:

    I thought the point of this forum/site was to debate, amongst other things, good/bad coding-practise?



    Indeed.

    Type inferernce has it's place, but don't use it just to make your code look Sexy/LinQy. If you mean a boolean, use a boolean. It makes you're code easier to read, and with more complicated datatypes also means that you get intellisense made available to you...

    Martin.

     

     



  • @muppetman said:

    Indeed.

    Type inferernce has it's place, but don't use it just to make your code look Sexy/LinQy. If you mean a boolean, use a boolean. It makes you're code easier to read, and with more complicated datatypes also means that you get intellisense made available to you...

    Martin.

    Intellisense is exactly the same, var is not like var in VB/javascript in the meaning of variant or something, it just tells the compiler to get the correct type at COMPILE time. So VS will threat the variable the same on the next line if you write bool or var, the tooltip on the var keyword will even show the correct type.



  • Often "var" can be useful in C#, but when I see it used for every single object/variable it makes me cringe. Especially something simple like a boolean type.

    Despite the fact that "var" in this case is essentially the same as "bool" surely it should be good practice to explicitly state the type?



  • IMO this is just a matter of habit. Nothing bad happens if you use var whenever possible. Since I'm currently rather using script languages like JavaScript and Groovy, where you use var resp. def all the time, I took me some time to figure out what exactly annoys you about that innocent looking line.



  • @ammoQ said:

    Nothing bad happens if you use var whenever possible. 

    Doesn't it lose out on strong type-checking?




  • @DaveK said:

    @ammoQ said:

    Nothing bad happens if you use var whenever possible. 

    Doesn't it lose out on strong type-checking?


    No it's still strongly typed.  The var keyword is just syntactic sugar.  I recommend using it all the time, because you never know when you may want to change the type from bool to some other data type ;) .



  • @frits said:

    @DaveK said:

    @ammoQ said:

    Nothing bad happens if you use var whenever possible. 

    Doesn't it lose out on strong type-checking?


    No it's still strongly typed.  The var keyword is just syntactic sugar.  I recommend using it all the time, because you never know when you may want to change the type from bool to some other data type ;) .

    Ok I'm going to ask a stupid question, because the Var keyword is new to me...

    How does C# tell what the type is supposed to be? I mean, in this case it's a bool because he's setting it to false right away. And I get that with classes it's not an issue because you specify the class name when you instantiate it.

    But what if you set it to something that can be stored by a dozen types, like 5? What if you set it to null, does it assume it's a nullable string or does it just remain some nebulous non-type?



  • @blakeyrat said:

    Ok I'm going to ask a stupid question, because the Var keyword is new to me...

    How does C# tell what the type is supposed to be? I mean, in this case it's a bool because he's setting it to false right away. And I get that with classes it's not an issue because you specify the class name when you instantiate it.

    But what if you set it to something that can be stored by a dozen types, like 5? What if you set it to null, does it assume it's a nullable string or does it just remain some nebulous non-type?

    5 will be int by default, .NET has some rules for this (1L will be long, 1U is an uint,...) which is also why can you can have a method that takes any object and when you pass it 5 it will still be an int.
    Can't use null because it can't defer the type then. The quick workaround is to use something like default(type).
    The same stuff is used when creating anonymous types. new { Name = "Test", Age = 24, NullableDate = default(DateTime?) } so we already have it here.



  •  @blakeyrat said:

    @frits said:

    @DaveK said:

    @ammoQ said:

    Nothing bad happens if you use var whenever possible. 

    Doesn't it lose out on strong type-checking?


    No it's still strongly typed.  The var keyword is just syntactic sugar.  I recommend using it all the time, because you never know when you may want to change the type from bool to some other data type ;) .

    Ok I'm going to ask a stupid question, because the Var keyword is new to me...

    How does C# tell what the type is supposed to be? I mean, in this case it's a bool because he's setting it to false right away. And I get that with classes it's not an issue because you specify the class name when you instantiate it.

    But what if you set it to something that can be stored by a dozen types, like 5? What if you set it to null, does it assume it's a nullable string or does it just remain some nebulous non-type?

    The compiler takes a look on the righthand side of the = There is evaluates the type of the assignment. That is then the type of the new variable. Only works with an assignment and no things like IDisposable d = new StringReader(...)



  • @blakeyrat said:

    @frits said:

    @DaveK said:

    @ammoQ said:

    Nothing bad happens if you use var whenever possible. 

    Doesn't it lose out on strong type-checking?


    No it's still strongly typed.  The var keyword is just syntactic sugar.  I recommend using it all the time, because you never know when you may want to change the type from bool to some other data type ;) .

    Ok I'm going to ask a stupid question, because the Var keyword is new to me...

    How does C# tell what the type is supposed to be? I mean, in this case it's a bool because he's setting it to false right away. And I get that with classes it's not an issue because you specify the class name when you instantiate it.

    But what if you set it to something that can be stored by a dozen types, like 5? What if you set it to null, does it assume it's a nullable string or does it just remain some nebulous non-type?

     The literal 5 is strongly typed, as an int32 I believe, so no ambiguity there.  Initializing a var to null will cause a compilation error.

     



  • @blakeyrat said:

    How does C# tell what the type is supposed to be? I mean, in this case it's a bool because he's setting it to false right away. And I get that with classes it's not an issue because you specify the class name when you instantiate it.

    But what if you set it to something that can be stored by a dozen types, like 5? What if you set it to null, does it assume it's a nullable string or does it just remain some nebulous non-type?

    var a=5 gets the type System.Int32 (5.GetType() gives the same result - Int32 is the default type for integer literals). var a=null is a compile error.

    The exact same feature is part of C++0x, except with "auto" instead of "var".



  • The following restrictions apply to implicitly-typed variable declarations:

    • var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.

    • var cannot be used on fields at class scope.

    • Variables declared by using var cannot be used in the initialization expression. In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);

    • Multiple implicitly-typed variables cannot be initialized in the same statement.

    • If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.

    You may find that var can also be useful with query expressions in which the exact constructed type of the query variable is difficult to determine. This can occur with grouping and ordering operations.

    The var keyword can also be useful when the specific type of the variable is tedious to type on the keyboard, or is obvious, or does not add to the readability of the code. One example where var is helpful in this manner is with nested generic types such as those used with group operations. In the following query, the type of the query variable is IEnumerable<IGrouping<string, Student>>. As long as you and others who must maintain your code understand this, there is no problem with using implicit typing for convenience and brevity.

    However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required.

    Taken from http://msdn.microsoft.com/en-us/library/bb384061.aspx



  • I really don't like var either. I know it's not technically weakly typed, as in Javascript, but it makes it so much more obvious what type it is when you do

    
    MyClass instance = SomeMethodThatReturnsMyClass()
    
    

    as opposed to

    
    var instance = SomeMethodThatReturnsMyClass()
    
    

    Yeah, yeah, Intellisense will help you there, I know. But I still like to be able to figure out what's going on from the source code as much as possible.



  •  Fun fact: This is one of the rare occasions where Visual Basic actually does things well. (The .NET version at least. You want to skip the paragraph about VB6 though, if you value your sanity)



  • The var keyword should ONLY be used with anonymous types....why???? Consider the following:

    class SimpleToy  { public void TurnOn(); }

    class Factory { public static SimpleToy Get() {...} }

    var x= Factory.Get();

    x.TurnOn(); 

    Now replace the Factory to return a nuclear bomb....the code will still compile, but it would have significantly different ramifications.

     



  • @PSWorx said:

     Fun fact: This is one of the rare occasions where Visual Basic actually does things well. (The .NET version at least. You want to skip the paragraph about VB6 though, if you value your sanity)

    Okay, as a self-described VB.NET hater, that is actually pretty neat.



  •  Thanks for the replies guys. A nice balanced mix of opinion - that's all I can ask for :-)



  • @dhromed said:

    I think the pattern:

    ClassName instanceName = new ClassName()

    is equally fucked.

     

    Really? I thought it was one of the cornerstones of object oriented programming, namely polymorphism.

    Disclaimer: I'm not a professional developer and my programming courses at University were many years ago.

    B



  • @havokk said:

    @dhromed said:

    I think the pattern:

    ClassName instanceName = new ClassName()

    is equally fucked.

     

    Really? I thought it was one of the cornerstones of object oriented programming, namely polymorphism.

    Disclaimer: I'm not a professional developer and my programming courses at University were many years ago.

    B

    I think the objection centers around the fact that you have redundant information: namely, the name of the class being instantiated is both before the variable and after the new keyword. A minor gripe, IMO.



  • @XIU said:

    when you see the showComment variable somewhere else you can just hover over it and also see that it's a boolean.
    Assuming your IDE does this and understands C#.



  • @toth said:

    @havokk said:

    @dhromed said:

    I think the pattern:

    ClassName instanceName = new ClassName()

    is equally fucked.

     

    Really? I thought it was one of the cornerstones of object oriented programming, namely polymorphism.

    Disclaimer: I'm not a professional developer and my programming courses at University were many years ago.

    B

    I think the objection centers around the fact that you have redundant information: namely, the name of the class being instantiated is both before the variable and after the new keyword. A minor gripe, IMO.

    Also, there is no polymorphism in assigning to a variable an instance of the very same class.



  • @miner49er said:

    "the time spent on these posts might have been better spent on useful code, so let's not get lost in useless details."

     

    I thought the point of this forum/site was to debate, amongst other things,[B] useless details[/B]?

     

     

    FTYF



  • @SQLDave said:

    @miner49er said:

    "the time spent on these posts might have been better spent on useful code, so let's not get lost in useless details."

     

    I thought the point of this forum/site was to debate, amongst other things, useless details?

     

     

    FTYFFY

     

     

    FTFM



  • @toth said:

    I think the objection centers around the fact that you have redundant information

    true.

    @toth said:

    A minor gripe, IMO.

    and also true; hence my earlier post about details.

    There are bigger WTFs to fry, as I see it. For example, the LOLboard here at the office now sports, among other things,  a picture of a road crossing that ends in a fence. I find this amusing.

     



  • @dhromed said:

    For example, the LOLboard here at the office now sports, among other things,  a picture of a road crossing that ends in a fence. I find this amusing.
     

    You probably enjoy Oddly Specific then?



  • @TheCPUWizard said:

    Now replace the Factory to return a nuclear bomb....the code will still compile, but it would have significantly different ramifications.
     

    Your example is very extreme and also unlikely; on the other hand, this behaviour could be desired. Consider:

        class FooBar { public int getPrimaryKey(); public static bool doSomething(int pimaryKey); }

    In such a case, the following code just needs to be recompiled when, for whatever reason, the type of primaryKey is changed to string:

          var key = fooBar.getPrimaryKey();

          FooBar.doSomething(key);

     BTW, since this thread is a serious discussion about coding, I'm moving it to "Coding related help& questions"



  • @lolwtf said:

    @XIU said:
    when you see the showComment variable somewhere else you can just hover over it and also see that it's a boolean.
    Assuming your IDE does this and understands C#.

    Except for the people that program in Notepad we only have 3 IDE's for .NET development: Visual Studio, MonoDevelop and SharpDevelop. All three have this feature, what IDE are you using then?



  • @Zecc said:

    @toth said:

    @havokk said:

    @dhromed said:

    I think the pattern:

    ClassName instanceName = new ClassName()

    is equally fucked.

     

    Really? I thought it was one of the cornerstones of object oriented programming, namely polymorphism.

    Disclaimer: I'm not a professional developer and my programming courses at University were many years ago.

    B

    I think the objection centers around the fact that you have redundant information: namely, the name of the class being instantiated is both before the variable and after the new keyword. A minor gripe, IMO.
    Also, there is no polymorphism in assigning to a variable an instance of the very same class.

    Not in this example but...

    First there are two things happening in this line

    1. ClassName instanceName; //Declaring an object of type ClassName
    2. instanceName = new ClassName();//Creating an instance of this class and assigning it to instanceName variable

    Now why both right? Because I can put in instanceName any child of ClassName and the compiler is not magical, it doesn't know so not a wtf in the context of c#

    var simply infer the type at compile time and put it but as in previous post it has limitations.

    Regards


  • ♿ (Parody)

    @TheCPUWizard said:

    Consider the following:

    class SimpleToy  { public void TurnOn(); }

    class Factory { public static SimpleToy Get() {...} }

    var x= Factory.Get();

    x.TurnOn(); 

    Now replace the Factory to return a nuclear bomb....the code will still compile, but it would have significantly different ramifications.

     But wouldn't that be true in *any* factory pattern?

    class Bomb : Simple Toy { public override void TurnOn { ka_boom(); } }

    class SimpleToy  { public virtual void TurnOn() {...} }

    class Factory { public static SimpleToy Get() { return new Bomb(); } }

    SimpleToy x= Factory.Get();

    x.TurnOn(); 



  • @XIU said:

    Except for the people that program in Notepad we only have 3 IDE's for .NET development: Visual Studio, MonoDevelop and SharpDevelop. All three have this feature, what IDE are you using then?
     

    I think that most people in C#-Land use VisualStudio, but I wouldn't be too surprised to learn that some people out there seriously use powerful editors like VIM, SlickEdit, UltraEdit etc. for C# development; masochists with bad taste might even choose Emacs for the task.

    It's easy to imagine that such editors might be smart enough to understand normal type declarations, but not the var keyword.



  • @Alex Papadimoulis said:

    @TheCPUWizard said:

    Consider the following:

    class SimpleToy  { public void TurnOn(); }

    class Factory { public static SimpleToy Get() {...} }

    var x= Factory.Get();

    x.TurnOn(); 

    Now replace the Factory to return a nuclear bomb....the code will still compile, but it would have significantly different ramifications.

     But wouldn't that be true in *any* factory pattern?

    class Bomb : Simple Toy { public override void TurnOn { ka_boom(); } }

    class SimpleToy  { public virtual void TurnOn() {...} }

    class Factory { public static SimpleToy Get() { return new Bomb(); } }

    SimpleToy x= Factory.Get();

    x.TurnOn(); 

     

    Right.  Plus if you cared about narrowing the specific type you would use casting or the "as" keyword and check for null.

     



  • @ammoQ said:

    @XIU said:

    Except for the people that program in Notepad we only have 3 IDE's for .NET development: Visual Studio, MonoDevelop and SharpDevelop. All three have this feature, what IDE are you using then?
     

    I think that most people in C#-Land use VisualStudio, but I wouldn't be too surprised to learn that some people out there seriously use powerful editors like VIM, SlickEdit, UltraEdit etc. for C# development; masochists with bad taste might even choose Emacs for the task.

    I guess it's theoretically possible, but if they're masochists, they'll enjoy not knowing what type the variable is. Right? Because they're masochists.



  • @ammoQ said:

    @XIU said:

    Except for the people that program in Notepad we only have 3 IDE's for .NET development: Visual Studio, MonoDevelop and SharpDevelop. All three have this feature, what IDE are you using then?
     

    I think that most people in C#-Land use VisualStudio, but I wouldn't be too surprised to learn that some people out there seriously use powerful editors like VIM, SlickEdit, UltraEdit etc. for C# development; masochists with bad taste might even choose Emacs for the task.

    It's easy to imagine that such editors might be smart enough to understand normal type declarations, but not the var keyword.

    Visual Studio is the compelling reason to use .Net.  If you prefer to develop with a development tool that doesn't completely understand the language, you might be better off using a different language.  One of the main reasons ASP.Net was designed like it was, was to let you use Visual Studio for code and still continue to use your favorite editor for markup.


  • @TheCPUWizard said:

    The var keyword should ONLY be used with anonymous types....why???? Consider the following:

    class SimpleToy  { public void TurnOn(); }

    class Factory { public static SimpleToy Get() {...} }

    var x= Factory.Get();

    x.TurnOn(); 

    Now replace the Factory to return a nuclear bomb....the code will still compile, but it would have significantly different ramifications.

    As has been said, not only does this "problem" have nothing to do with the var keyword (since it happens in any polymorphic structure), anyone who would completely change a return type like this is TRWTF.

     

    As for var, consider this code:

    IEnumerable<int> iterator = FunctionGetInts();

     

    What's wrong with that code?  Nothing, you say?  What if you look at the declaration of FunctionGetInts:

    public IList<int> FunctionGetInts()

     

    You can now see that FunctionGetInts is returning an IList, but you're simply using it as an IEnumerable, so you've lost all the functionality that IList gives you, and Intellisense won't know the difference.  However, if you were to instead use this:

    var iterator = FunctionGetInts();

    it would be of type IList, and you still have the extra functionality that IList provides.

     

    The point is this: the compiler knows the type better than you, so let it help!



  • Sutherland, What you are illustrating is proper polymorphic behaviour. If the "FuctionGetInts()" all of a sudden was reworked to return doubles (a WTF given the name, but that is irrelevant) then you would get a compiler error (which is good). But if you declared iterator as var is would still compile. Even more if you had

     foreach (var item in iterator)  f(item)

     you would ge one oif two possible outcomes:

     1) A failure - at a line that is completely different than where the actual "issue" (the change in return type) is.

     2) A call to a completely different overload.

     In the second case, it is very unlikely that a complete code review of the function that was changed would clearly show this (possibly breaking) change.



  • @TheCPUWizard said:

    Sutherland, What you are illustrating is proper polymorphic behaviour.

    No, what I am illustrating is that the compiler can better determine types than you can.  There was polymorphism involved, though, so I can see where you would be confused.

    @TheCPUWizard said:

    If the "FuctionGetInts()" all of a sudden was reworked to return doubles (a WTF given the name, but that is irrelevant)

    No, a WTF regardless of the name

     

    Let's try another case (and this is taken out of Chapter 4 of More Effective C#, which I highly suggest reading):

    public IEnumerable<string> FindCustomersStartingWith(string start)

    {

    IEnumerable<string> q = from c in db.Customers select c.ContactName;

    var q2 = q.Where(s => s.StartsWith(start))

    return q2

    }

     

    What's wrong with this code?  What's wrong is that q is declared as an IEnumerable.  The interface that's actually returned is IQueryable.  When the second part of the query is compiled, it uses Enumerable.Where instead of Queryable.Where, and Queryable can combine the entire thing into one expression tree.  Just by declaring a type, you've wrecked the performance of not only the function, but of the network.



  • Sutherland...

    #1, I was not in any way confused.
    #2, As part of my professional life I do technical reviews of many books (including many by Addison-Wesley)
    #3, I know Bill, Scott, and about half of the people on the "Praises" page personally.

     It *IS* a very good book....but one must also consider the publication dates (2004 & 2008). They were both "leading edge" books at time of publication. Some of recommendations do not coincide with the latest .Net Framework Guidlines. This does not make them wrong or even bad, simply that experience in using the features over a period of years has produced additional insight into what really works well inh the long run (yes, the incorrect use of IEnumerable vs. IQueryable [or var] is still a FAIL).

    One thing I have found very revealing is Scott Meyers' comments when he wrote the intro for "Modern C++ Design"....I think you would find it an interesting read about why he specifically did not cover certain topics when we wrote the seminal "Effective C++" series. He has also written articles and postings about some of the changes in what is "effective" have been for C++ since the time when the books were written.



  • Good to know.  Any C# books you would recommend other than those two? (Or general programming books that apply to any language?)

    What are the recommendations that don't apply anymore?



  • The # 1 book I am recommending to anyone using VS-2010 is "Professional Application LifeCycle Management using Visual Studio". I suggest that people sit and do a full read (nnot a skip or browse) to see a set of processes that cover the complete process of developing an application. I then recomend that they implement the processes/techniques as covered in the book, making alterations as they find legitimate reasons why their specific project/team/environment warrants such a change. All of these changes should be documented (a WIKI is great!)

     I have done this process with a few clients, and the overall results have been impressive. In most cases there were large areas where the team did not even know capabilities existed. There were also many cases where the team had "figured out how..by experimentation" and really missed the mark. Of course, there were also many cases where there wer legitimate reasons for implementing/following a different paradigm.

     The value is that this gives a cohesive starting point. Wen most teams try to create an environment from scratch, they only see their current and past experiences, and not not see "what can be". As a result they approach tends "to go down rabbit holes" and either miss the mark, or cost alot of money/time getting to a good solution.

     Even though I have had a decent "process" for years, and had trained other teams on my methdology...I have made some serious adjustments to the way I do things.

     I am traveling right now, but when I get back to homebase early next week, I will pull together some of the books that I regularly wear out and need to replace....

    As far as changes in recommendations, one of the simplest things to do is to compare the first and second editions of the Framework Design Guidelines. I caution *against* using MSDN help files, as (unfortunately) too many of the pages are still copy/paste of v1.x methodologies (Especially in example snippets).

     Finally, *do* read all of the featured bloggers on msdn.microsoft.com. There is alot of good information that often pops up in unexpected blogs (such as a recent case where a post on Mobile computing referenced some of the new Async software.

     



  • @TheCPUWizard said:

    If the "FuctionGetInts()" all of a sudden was reworked to return doubles (a WTF given the name, but that is irrelevant) then you would get a compiler error (which is good).

    Not in C# 4.0. With the added support for covariance on the IEnumerable<T> interface, it is perfectly valid to cast an instance implementing IList<double> to IEnumerable<int>.



  • @Ragnax said:

    @TheCPUWizard said:
    If the "FuctionGetInts()" all of a sudden was reworked to return doubles (a WTF given the name, but that is irrelevant) then you would get a compiler error (which is good).
    Not in C# 4.0. With the added support for covariance on the IEnumerable<T> interface, it is perfectly valid to cast an instance implementing IList<double> to IEnumerable<int>.

     Depends on the direction....for an "in" specified collection (where you can only insert items) that would be true. For an "out" specified collection (where you can only retrieve items), the reverse would be true. The "root rule" is that the the elements must be castable in the direction you are performing co/contra variance....

     Even with this case, my point was that if the type radically changes (using numeric types for the example was a bad idea), it is usually a bad idea to allow the compiler to radically alter behavior without altering the code to acknowledge the same.

     Perhaps a better example would be if the original code returned an Engine (Motor), and the Engine class supported a "Kill" method (as in "kill the engine == shut off the engine"). Later the code is changed so that it returns a Horse. An animal can be Killed, so that method name may still be syntactically valid, but the actual action (turning off a mechanical device vs. killing a living animal) should be a big enough difference in actiuon, that a person would want to make a deliberate decision that the actual action is correct.



  • The compiler would likely still catch this, as the implementation details of "killing" an engine would be different from "killing" a horse. Unless you have a horse with a kill switch, ofc. :)



  • @RaspenJho said:

    The compiler would likely still catch this, as the implementation details of "killing" an engine would be different from "killing" a horse. Unless you have a horse with a kill switch, ofc. :)
    But surely the point of polymorphism is that you can just go and tell your object to kill itself, and it binds to the correct action at runtime?



  • @RaspenJho said:

    The compiler would likely still catch this, as the implementation details of "killing" an engine would be different from "killing" a horse. Unless you have a horse with a kill switch, ofc. :)

     

    No, the compiler will call any method which matches the signature. The "implementation details" do not matter.



  • @Scarlet Manuka said:

    @RaspenJho said:
    The compiler would likely still catch this, as the implementation details of "killing" an engine would be different from "killing" a horse. Unless you have a horse with a kill switch, ofc. :)
    But surely the point of polymorphism is that you can just go and tell your object to kill itself, and it binds to the correct action at runtime?

     Polymorphism is for items within a defined class hierarchy. Calling a method on any random object that could possibly exist, simply because that object has one method with a given signature is radically different - and especially dangerous. Effectively you have removed all type related "safety"...it the the equivilant of having "Option EXplicit Off" in VB and declaring everything as "Dim foo" without specifying the type.

     

     



  • That makes sense...

    I would however expect that a horse class that implements a "Kill" method would end up with a dead horse.


Log in to reply