Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the reason to hide a method with the new keyword, when only returning base.method?

I found the following code snippet in the DbSet Class of the EntityFramework:

public new Type GetType()
{
  return base.GetType();
}

I have no idea why the base method is hidden, all the base classes have the method implemented calling base.

This is object.GetType():

[SecuritySafeCritical]
[__DynamicallyInvokable]
[MethodImpl(MethodImplOptions.InternalCall)]
public extern Type GetType();

This is in the DbQuery class:

/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public new Type GetType()
{
  return base.GetType();
}

And this is in the DbSet (DbSet<TEntity> : DbQuery<TEntity>) class:

/// <inheritdoc />
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
[EditorBrowsable(EditorBrowsableState.Never)]
public new Type GetType()
{
  return base.GetType();
}

Why or when would you use the new keyword and then call the base implementation?

like image 747
Mafii Avatar asked Sep 06 '17 12:09

Mafii


2 Answers

Let's consider the alternatives.

  1. Don't override or new anything

    Problem: There's no code on which to apply attributes.

  2. Just override it

    Problem: GetType is not virtual.

So you're left using new with a call to base.

The real question is what is so important about [EditorBrowsable(EditorBrowsableState.Never)] that they went to all this trouble? My only guess is that they felt that developers would confuse GetType with ElementType in intellisense.

like image 139
John Wu Avatar answered Nov 07 '22 06:11

John Wu


I think one reason you would use the new keyword is when you want to change the access modifier. If your method is protected in the base class you can make it public in your child class using the new keyword.

like image 38
Madalin Sisu Avatar answered Nov 07 '22 04:11

Madalin Sisu