C# Default scope resolution
Asked Answered
K

5

6

I have inherited a c# class 'Button' (which I can't change) which clashes with the BCL class 'Windows.Forms.Button'. Normally, Id be very happy to go:

MyPackage.MyClass.Button;

But there are a large number or references to this class which is a pain to have to re-type.

Is there any way to get the compiler (linker?) to default to using the customised version of Button over the BCL version?

Keever answered 6/10, 2008 at 13:16 Comment(0)
M
21

Add this to the top of the file:

using MyButton = MyPackage.MyClass.Button;

Now you can reference your custom button using a distinct name. You may need to do something similar for the stock button if you use that anywhere in the same file.

Mullis answered 6/10, 2008 at 13:22 Comment(4)
This was good to see. I don't think it worked in earlier versions of .NET and I didn't know it was added.Lingcod
Works from at least 2.0 on up.Mullis
Actually I believe this sort of aliasing has been available from C# 1.0. It's namespace aliases (e.g. alias::typename) which was introduced in C# 2.0.Taliesin
This has been available since at least the betas of 1.0. I recall using this syntax in a project I did in .Net 1.0 Beta 2.Sloan
L
4

if you want to use it by default, replace

using Windows.Forms;

with

using MyPackage.MyClass;

If you do that, you'll need to fully qualify all the buttons from Windows.Forms.

Or, if you want to, you can alias the namespace

using My = MyPackage.MyClass;
//... then
My.Button b = ...

Or alias the button

using MyButton = MyPackage.MyClass.Button;
Ladida answered 6/10, 2008 at 13:25 Comment(0)
I
2

You could remove using Windows.Forms; from the top of the code. That would of course mean that you would have to reference all Windows.Forms items specifically.

Ishmaelite answered 6/10, 2008 at 13:20 Comment(1)
Nice idea, although given the rest of the classes functionality it leaves me in about the same position as before!Keever
C
0

You can at least make it a small bit less painful/wordy with "using":

using MPMC = MyPackage.MyClass;

then you can say:

MPMC.Button
Communicable answered 6/10, 2008 at 13:24 Comment(0)
K
0

It appears that I can do the following:

using Button = MyPackage.MyClass.Button;

works and it preserves all references within the code to Button. Although Im tempted not to go down this route as it is still ambiguious (at least to the reader) which Button is being used.

Keever answered 6/10, 2008 at 13:30 Comment(2)
Read it again: you can set your own name for the button class that's different from button.Mullis
Im aware of that. However, due to the already horrible nature of the code base I was thinking it might be better to stick with the names that are already there e.g. 'Button' rather than another name e.g. 'CustomButton'. Although you could be right is suggesting a unique name.Keever

© 2022 - 2024 — McMap. All rights reserved.