C# 2008 aka C# 3.0Discuss the Visual C# 2008 (aka C# 3.0) language
Welcome to the p2p.wrox.com Forums.
You are currently viewing the C# 2008 aka C# 3.0 section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
With extension methods you only have access to the public properties and methods of the class you are extending.
With inheritance you have access to protected properties and methods, and you can also do things like override virtual methods etc.
Also, with inheritance all your code for a particular class will be in the same place. Whereas with extension methods your code will relating to a particular class will be in another, none obvious location.
__________________
/- Sam Judson : Wrox Technical Editor -/
Here is one situation that inheritance can benefit you. First letâs take a look at the extension way:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SomeNamespace
{
class Program
{
static void Main(string[] args)
{
var p = new Program();
p.foo();
}
/*public void foo()
{
Console.WriteLine("1");
}*/
}
static class Extended
{
public static void foo(this Program p)
{
Console.WriteLine("2");
}
}
}
Assume you donât have control over class âProgramâ and may even donât have access to source code of it. Run this program, it prints 2; uncomment what I commented out, and run it again, you got 1 â the behavior changed, there is no warning and no error, you might end up spend hours to debug before you find out whatâs going on.
Now look at the inheritance way:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SomeNamespace
{
class Program
{
static void Main(string[] args)
{
var p = new Extended();
p.foo();
}
public void foo()
{
Console.WriteLine("1");
}
}
class Extended : Program
{
public void foo()
{
Console.WriteLine("2");
}
}
}
Visual Studio gives you a warning saying ââSomeNamespace.Extended.foo()â hides inherited member âSomeNamespace.Program.foo()â. Use the new keyword if hiding is intendedâ. This warning could save you hours of debugging time. (Add the new keyword as suggested will remove the warning.)
Last edited by PeterPeiGuo; March 2nd, 2010 at 06:37 PM..
The Following User Says Thank You to PeterPeiGuo For This Useful Post: