Question

Is new keyword needed to hide members?

Asked by: brettr

Is the new keyword needed to hide base class members?  I can see no difference on the child member if new is used or not.  Only difference is that it removes the compiler warning.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-02-14 at 21:52:50ID24144473
Topics

C# Programming Language

,

.NET

Participating Experts
3
Points
500
Comments
16

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. KeyWord Finder
    Hi, I've been looking for a little searcher for just one page, a keyword or phrase finder. I'd like to put it is several of my pages/htmls that contain a lot of of data to make it easy for people to find stuff. Can you offer any ideas? Can you help? Please see http://www.geo...
  2. virtual & override keywords
    Hi experts !! Wanna know the point of using virtual keyword for a methods declaration & override keyword in a subclasses implementation for a certain inherited method. class A { public virtual void methodA() { Console.WriteLine("base methodA()"...
  3. Meta tag keywords
    Is it possible to hide the <META> tag so that people cannot steal the keywords?
  4. data hiding in C
    how we can achive data hiding in C .
  5. 'new' keyword in C#, member-hiding
    hello, I have a class called "NewTable" that inherits from System.Web.UI.WebControls.Table. In the "NewTable" class, I want to hide the "Rows" property of the base class so that it is not accessible. For instance, I don't want this statement t...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Frosty555Posted on 2009-02-14 at 22:49:54ID: 23643856

The "New" keyword is used to set the variable equal to a new instance of an object. Normally object variables are initially set to NULL until they are explicitly given a value.

If you want to hide the members of a base class, use the "Private" or "Protected" keywords before the declaration. E.g.

Private MyObject oSomething;

Private means nobody can see it except the class itself. Protected means only the class and it's derived subclasses can see it, but a caller can't.

 

by: ImperdonatoPosted on 2009-02-14 at 23:06:14ID: 23643881

Yes and No.
Yes because a new modifier hides inherited members from a base class member,
           ex:
            public class baseClass {
                 public void SomeMethod() {}
           }

           public class derivedClass : baseClass {
                 new public void SomeMethod() {}
           }
This member (SomeMethod) declared with the new modifier, will hide the same method from the base class.

No because a new operator  creates objects and call constructors of the respective class.
           ex: classA objA = new classA();

Also read: http://msdn.microsoft.com/en-us/library/51y09td4(VS.71).aspx.

Hope that helps.

 

by: gnoonPosted on 2009-02-14 at 23:20:47ID: 23643905

Yes. The 'new' modifier is mainly used for hiding the non virtual members, especially methods.
It does not replace the original like 'override'. Casts the instance to Base class to access the original version of member.

Visit here to get more helpful information
http://geekswithblogs.net/mohamed/articles/28613.aspx

 

by: brettrPosted on 2009-02-14 at 23:27:54ID: 23643918

Imperdonato and gnoon seem to get what I'm asking.  This isn't anything to do with creating objects.

@gnoon
Why do you say "Yes"?  I can leave off the new keyword and still hide members.  Please explain why you disagree.

 

by: ImperdonatoPosted on 2009-02-14 at 23:48:38ID: 23643954

A couple of points which might clear the picture somewhat:
                                     1. You can use new for non-virtual methods, events and properties(but you can not use override for these).
2.
Take an example:

derivedClass derivedObj = new derivedClass();
baseClass baseObj = derivedObj;
baseObj.SomeMethod();
-------------

 If the derivedObj.SomeMethod() is defined as "new", the above code will call the baseClass version. If it is defined as "override", it will call the derivedClass version.


3. If we have not specified any of these (new or override), the resulting output is similar to if we have used "new"; though the compiler generates a warning.

4. Using new you can change the return type of a method or property. Plus, it can help making a derived class more strongly typed than the base.

5. Consider this: A new version of a base class may be released which happens to introduce a method with the same name as a method in your derived class. Since these two methods have no relationship to eachother, except that the happen to have the same name, you certainly don't want to start overriding the new base method. new takes care of this.

Hope that helps.

 

by: gnoonPosted on 2009-02-14 at 23:52:44ID: 23643963

Sorry for confused word ;-) I mean yes because it just removes the warning of compiler. If 'new' is not specified, the member will behave as 'new' keyword were present.

 

by: ImperdonatoPosted on 2009-02-14 at 23:56:47ID: 23643977

And yes, you can leave off the new keyword, and hide members. I personally rarely use new as a modifier.
So No, we do not need the new keyword in most of the cases, unless we need to cater to some special scenario which only "new" can take care of.

 

by: brettrPosted on 2009-02-15 at 09:09:15ID: 23645564

@gnoon
Thanks for clarifying.

@Imperdonato
Your last post shows you are agreeing that new on derived methods/properties has no affect, which is true.   But the post just before it (ID: 23643954) says differently:

4. Using new you can change the return type of a method or property. Plus, it can help making a derived class more strongly typed than the base.

You're saying "new" allows you to change the return type of derived properties/methods.  This is not true.  Leave off "new" and you can still accomplish the same thing.   "new" also does nothing for making those members strongly typed.   Please prove me wrong.

 

by: ImperdonatoPosted on 2009-02-15 at 10:32:03ID: 23645914

@Imperdonato
Your last post shows you are agreeing that new on derived methods/properties has no affect, which is true.   But the post just before it (ID: 23643954) says differently:
No. Read my posts again. :)
                         
4. Using new you can change the return type of a method or property. Plus, it can help making a derived class more strongly typed than the base.
Yes. This means if you use the new modifier, the above thing is accomplished. However, if you've carefully read my post, (specifically Poine #3) then you would know that even if you leave the new modifier, Visual Studio compiler would take it as if you'd specified the keyword (other than a warning of course, and IMO, no warnings should be ignored, if ofcourse avoidable- which in this case is).

You're saying "new" allows you to change the return type of derived properties/methods.  This is not true.  Leave off "new" and you can still accomplish the same thing.  

Yes. And I repeat "new" allows you to change the return type of derived properties/methods- and this is true. Just because compiler gives you the ease of not specifying the keyword, doesn't mean you should take the credit away from it :\

"new" also does nothing for making those members strongly typed.   Please prove me wrong.
Okay. Consider this example:

public class baseClass{
    public void SomeMethod(){
        Console.WriteLine("This is base.");
    }
}

public class derivedClass: baseClass{
    new public void SomeMethod(){
        Console.WriteLine("This is the derived one");
    }
}

Now if we make calls like
baseClass baseObj = new baseClass();
derivedClass derivedObj = new derivedClass();
baseObj.SomeMethod();
derivedObj.SomeMethod();
The first call would call the base class' SomeMethod and would display "This is base.", and
the second call is calling SomeMethod from the derived class (i.e, "This is the derived one" would be displayed on the screen)

I hope we agree till this point.

Now, if you agree above, then that means the new modifier has made the member (the method in this case); strongly typed!
Read: http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/2ea38b96-921c-4218-8c28-168f33b4bf62/)

Let me know if you still have doubts. :-)

 

by: brettrPosted on 2009-02-15 at 12:10:40ID: 23646307

And I repeat "new" allows you to change the return type of derived properties/methods- and this is true.
Still disagree with you on that.  You don't need new to change the return type.  "new" has zero affect but to be explicit to the compiler.

I hope we agree till this point... Now, if you agree above, then that means the new modifier has made the member (the method in this case); strongly typed!
No, we don't agree and the link you sent does nothing for your case here.  The method is void and returns nothing.  Even if it did return something, you can change the derived member's return type without "new".   Further, if you leave off new in your example, you'll notice the outcome is exactly the same.  "new" only tells the compiler we are being explicit that the derived method is unrelated to the base.  It does nothing for functionality or manipulates data in anyway.  Strongly type is up to the developer.  "new" doesn't do anything for  the member in regards to strongly typed.

 

by: ImperdonatoPosted on 2009-02-15 at 20:36:49ID: 23646952

Yup. But just to quote me from my last post: "Just because compiler gives you the ease of not specifying the keyword, doesn't mean you should take the credit away from it :\"
And I repeat again, just because compiler gives you an option not to specify the new modifier, doesnt mean new is not acting at the background. Hope you get it this time.
And btw, the example that I'd given earlier, does prove that with new you accomplish strongly typed members. SomeMethod becomes strongly typed, because no matter what, that is the method which will be called, unlike the example I stated in my post (ID: 23643954) Point # 5.
Just because you've the liberty not to specify the keyword, doesn't mean you are not using it. It's being used, though you might not know it.
(Similar to if you declare a class without specifying an access modifier, the compiler will take it as a private)


 

by: brettrPosted on 2009-02-15 at 21:23:15ID: 23647143

SomeMethod becomes strongly typed, because no matter what, that is the method which will be called

Again, it is void.  Where are you coming up with strongly typed?  It will be called regardless if new is there or not.  If you want a return type, fine.  C# is strongly typed and in the case of derived members, unless you are doing something dynamic, they will be strongly typed whether you want them to or not.   You mentioned of strongly typed in this case is irrelevant.

In regards to your point #5, you will only override if you use that keyword.  Otherwise, the child class member is used, "new' or not.

 

by: ImperdonatoPosted on 2009-02-15 at 22:43:45ID: 23647356

Again, it is void.  Where are you coming up with strongly typed?  
And why not?

It will be called regardless if new is there or not.  
Never denied that.

In regards to your point #5, you will only override if you use that keyword.  Otherwise, the child class member is used, "new' or not.
Consider this:

public class baseClass{
    public void SomeMethod(){
        Console.WriteLine("This is base.");
    }
}

public class derivedClass: baseClass{
    public void SomeMethod(){
        Console.WriteLine("This is the derived one");
    }
}

baseClass baseObj = new baseClass();
derivedClass derivedObj = new derivedClass();
baseObj.SomeMethod();
derivedObj.SomeMethod();

The output will of course be similar to the one we had seen earlier.
Now, suppose somebody makes a change to derivedClass' SomeMethod:
public class derivedClass: baseClass{
    public void SomeMethod(string id){
        Console.WriteLine("This is the derived one. Id: " + id.ToString());
    }
}

Now, if we make calls like
baseClass baseObj = new baseClass();
derivedClass derivedObj = new derivedClass();
baseObj.SomeMethod();
derivedObj.SomeMethod();


What do you think the output will be?

"This is base."
"This is base."


Now why this? Because you dint explicitly specified the new modifier, the compiler didn't give you an error earlier, after you changed derviedClass.SomeMethod.
So that lead to the base class method being called, though the callers' intention was to call SomeMethod of the derivedClass.
In large projects, this has a very high probability of occurrence.

I guess I have been clear enough this time, and that you will get it now.
Thanks.

 

by: ImperdonatoPosted on 2009-02-15 at 22:46:05ID: 23647364

Because you dint explicitly specified the new modifier, the compiler didn't give you an error earlier, after you changed derviedClass.SomeMethod.
^^Sorry, the compiler will give you a warning, not an error.

 

by: brettrPosted on 2009-02-15 at 22:55:37ID: 23647392

I'm not sure what you are wanting me to get.  

public void SomeMethod(string id){...}

is a completely different method and has nothing to do with strongly typed.  gnoon summed up the answer nicely and you were heading in a good direction as noted by my post ID: 23643918.  But now you've only demonstated how very confused you are.

 

by: ImperdonatoPosted on 2009-02-15 at 23:10:18ID: 23647428

But now you've only demonstated how very confused you are.
Yeah right!
I don't really understand, where your confusion really is. My last post clearly gives an example to demonstrate the point I have been stressing.
Anyways, since this seems to be heading nowhere, plus the post has been closed, I won't be posting anymore. Later.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...