C# IS possible to name a method in class named new? - c#

example:
class document
{
public void new()
{
}
public void save()
{
}
}
visual studio claim that new is red-underlined with error.
I need that all is lower-cased to arrange cleanliness
For those seen this Questions:*
**(Answer)C# Naming rule violation: Words must be begin with Upper Cases!!!

NO, you can't since new is a keywoard. But, YES, you can escape keywords by # if accepted.
class document
{
public void test()
{
this.#new();
}
public void #new()
{
Console.WriteLine();
}
}
C# suggests using upper camel case in class name and method name.
Since keywords are in lower cases, upper camel case names, like void New(), are unaffected.

No you cannot use keywords as identifiers. See article https://msdn.microsoft.com/en-us/library/x53a06bb.aspx.

Related

How to call Method's Class Name dynamically?

Is it possible to use an input variable as a Method's Class Name?
What I'm using now:
Switch/Case with multiple Namespace.Class.Method()'s.
Each Codec Method is in its own Class.
public static void SetControls(string codec_SelectedItem)
{
switch (codec_SelectedItem)
{
case "Vorbis":
Codec.Vorbis.Set();
break;
case "Opus":
Codec.Opus.Set();
break;
case "AAC":
Codec.AAC.Set();
break;
case "FLAC":
Codec.FLAC.Set();
break;
case "PCM":
Codec.PCM.Set();
break;
}
}
Trying to simplify:
A single Method with a dynamic Class.
Use SelectedItem as Method's Class Name.
public static void SetControls(string codec_SelectedItem)
{
Codec.[codec_SelectedItem].Set();
}
Just make a dictionary with instances of the differenct codecs, initialize the dictionary a single time with all codecs. And then get any codec by name whenever you need it. Each codec must be a separate non-static class implementing a ICodec interface you create.
Example, unvalidated c#, to give you the gist:
private static Dictionary<string, ICodec> _codec;
public static void Initialize()
{
_codec = new Dictionary<string, ICodec> {
{ "Vorbis", new VorbisCodec() }
{ "Opus", new OpusCodec() }
};
}
public static void SetControls(string codecName)
{
_codec[codecName].set();
}
public interface ICodec
{
void set();
}
Addition as you commented to have it even more compact:
You can also use reflection to get a class by name, instantiate it and then call the .set() method:
((ICodec) Activator.CreateInstance(Assembly.GetExecutingAssembly().GetType(codecClassNameHere))).set();
I advise against it though. Code should also be readable. The Dictionary approach shows very cleanly what's going on. Reflection hides that, this is often more annoying for maintaining the code later on, than the "coolness" of making it very compact with reflection now :)

c# use base type generic parameter type name in derived class [duplicate]

I want to create an alias for a class name. The following syntax would be perfect:
public class LongClassNameOrOneThatContainsVersionsOrDomainSpecificName
{
...
}
public class MyName = LongClassNameOrOneThatContainsVersionOrDomainSpecificName;
but it won't compile.
Example
Note This example is provided for convenience only. Don't try to solve this particular problem by suggesting changing the design of the entire system. The presence, or lack, of this example doesn't change the original question.
Some existing code depends on the presence of a static class:
public static class ColorScheme
{
...
}
This color scheme is the Outlook 2003 color scheme. i want to introduce an Outlook 2007 color scheme, while retaining the Outlook 2003 color scheme:
public static class Outlook2003ColorScheme
{
...
}
public static class Outlook2007ColorScheme
{
...
}
But i'm still faced with the fact that the code depends on the presence of a static class called ColorScheme. My first thought was to create a ColorScheme class that I will inherit from either Outlook2003 or Outlook2007:
public static class ColorScheme : Outlook2007ColorScheme
{
}
but you cannot inherit from a static class.
My next thought was to create the static ColorScheme class, but make Outlook2003ColorScheme and Outlook2007ColorScheme classes non-static. Then a static variable in the static ColorScheme class can point to either "true" color scheme:
public static class ColorScheme
{
private static CustomColorScheme = new Outlook2007ColorScheme();
...
}
private class CustomColorScheme
{
...
}
private class Outlook2008ColorScheme : CustomColorScheme
{
...
}
private class Outlook2003ColorScheme : CustomColorScheme
{
...
}
but that would require me to convert a class composed entirly of readonly static Colors into overridable properties, and then my ColorScheme class would need to have the 30 different property getters thunk down into the contained object.
That's just too much typing.
So my next thought was to alias the class:
public static ColorScheme = Outlook2007ColorScheme;
But that doesn't compile.
How can I alias a static class into another name?
Update: Can someone please add the answer "You cannot do this in C#", so I can mark that as the accepted answer. Anyone else wanting the answer to the same question will find this question, the accepted answer, and a number of workarounds that might, or might not, be useful.
I just want to close this question out.
You can’t. The next best thing you can do is have using declarations in the files that use the class.
For example, you could rewrite the dependent code using an import alias (as a quasi-typedef substitute):
using ColorScheme = The.Fully.Qualified.Namespace.Outlook2007ColorScheme;
Unfortunately this needs to go into every scope/file that uses the name.
I therefore don't know if this is practical in your case.
You can make an alias for your class by adding this line of code:
using Outlook2007ColorScheme = YourNameSpace.ColorScheme;
You cannot alias a class name in C#.
There are things you can do that are not aliasing a class name in C#.
But to answer the original question: you cannot alias a class name in C#.
Update: People are confused why using doesn't work. Example:
Form1.cs
private void button1_Click(object sender, EventArgs e)
{
this.BackColor = ColorScheme.ApplyColorScheme(this.BackColor);
}
ColorScheme.cs
class ColorScheme
{
public static Color ApplyColorScheme(Color c) { ... }
}
And everything works. Now i want to create a new class, and alias ColorScheme to it (so that no code needs to be modified):
ColorScheme.cs
using ColorScheme = Outlook2007ColorScheme;
class Outlook2007ColorScheme
{
public static Color ApplyColorScheme(Color c) { ... }
}
Ohh, i'm sorry. This code doesn't compile:
My question was how to alias a class in C#. It cannot be done. There are things i can do that are not aliasing a class name in C#:
change everyone who depends on ColorScheme to using ColorScheme instead (code change workaround because i cannot alias)
change everyone who depends on ColorScheme to use a factory pattern them a polymorphic class or interface (code change workaround because i cannot alias)
But these workarounds involve breaking existing code: not an option.
If people depend on the presence of a ColorScheme class, i have to actually copy/paste a ColorScheme class.
In other words: i cannot alias a class name in C#.
This contrasts with other object oriented languages, where i could define the alias:
ColorScheme = Outlook2007ColorScheme
and i'd be done.
You want a (Factory|Singleton), depending on your requirements. The premise is to make it so that the client code doesn't have to know which color scheme it is getting. If the color scheme should be application wide, a singleton should be fine. If you may use a different scheme in different circumstances, a Factory pattern is probably the way to go. Either way, when the color scheme needs to change, the code only has to be changed in one place.
public interface ColorScheme {
Color TitleBar { get; }
Color Background{ get; }
...
}
public static class ColorSchemeFactory {
private static ColorScheme scheme = new Outlook2007ColorScheme();
public static ColorScheme GetColorScheme() { //Add applicable arguments
return scheme;
}
}
public class Outlook2003ColorScheme: ColorScheme {
public Color TitleBar {
get { return Color.LightBlue; }
}
public Color Background {
get { return Color.Gray; }
}
}
public class Outlook2007ColorScheme: ColorScheme {
public Color TitleBar {
get { return Color.Blue; }
}
public Color Background {
get { return Color.White; }
}
}
try this:
using ColorScheme=[fully qualified].Outlook2007ColorScheme
I'm adding this comment for users finding this long after OP accepted their "answer".
Aliasing in C# works by specifying the class name using it's fully qualified namespace. One defined, the alias name can be used within it's scope.
Example.
using aliasClass = Fully.Qualified.Namespace.Example;
//Example being the class in the Fully.Qualified.Namespace
public class Test{
public void Test_Function(){
aliasClass.DoStuff();
//aliasClass here representing the Example class thus aliasing
//aliasClass will be in scope for all code in my Test.cs file
}
}
Apologies for the quickly typed code but hopefully it explains how this should be implemented so that users aren't mislead into believing it cannot be done in C#.
Aliasing the way that you would like to do it will not work in C#. This is because aliasing is done through the using directive, which is limited to the file/namespace in question. If you have 50 files that use the old class name, that will mean 50 places to update.
That said, I think there is an easy solution to make your code change as minimal as possible. Make the ColorScheme class a facade for your calls to the actual classes with the implementation, and use the using in that file to determine which ColorScheme you use.
In other words, do this:
using CurrentColorScheme = Outlook2007ColorScheme;
public static class ColorScheme
{
public static Color ApplyColorScheme(Color c)
{
return CurrentColorScheme.ApplyColorScheme(c);
}
public static Something DoSomethingElse(Param a, Param b)
{
return CurrentColorScheme.DoSomethingElse(a, b);
}
}
Then in your code behind, change nothing:
private void button1_Click(object sender, EventArgs e)
{
this.BackColor = ColorScheme.ApplyColorScheme(this.BackColor);
}
You can then update the values of ColorScheme by updating one line of code (using CurrentColorScheme = Outlook2008ColorScheme;).
A couple concerns here:
Every new method or property definition will then need to be added in two places, to the ColorScheme class and to the Outlook2007ColorScheme class. This is extra work, but if this is true legacy code, it shouldn't be a frequent occurence. As a bonus, the code in ColorScheme is so simple that any possible bug is very obvious.
This use of static classes doesn't seem natural to me; I probably would try to refactor the legacy code to do this differently, but I understand too that your situation may not allow that.
If you already have a ColorScheme class that you're replacing, this approach and any other could be a problem. I would advise that you rename that class to something like ColorSchemeOld, and then access it through using CurrentColorScheme = ColorSchemeOld;.
I suppose you can always inherit from the base class with nothing added
public class Child : MyReallyReallyLongNamedClass {}
UPDATE
But if you have the capability of refactoring the class itself: A class name is usually unnecessarily long due to lack of namespaces.
If you see cases as ApiLoginUser, DataBaseUser, WebPortalLoginUser, is usually indication of lack of namespace due the fear that the name User might conflict.
In this case however, you can use namespace alias ,as it has been pointed out in above posts
using LoginApi = MyCompany.Api.Login;
using AuthDB = MyCompany.DataBase.Auth;
using ViewModels = MyCompany.BananasPortal.Models;
// ...
AuthDB.User dbUser;
using ( var ctxt = new AuthDB.AuthContext() )
{
dbUser = ctxt.Users.Find(userId);
}
var apiUser = new LoginApi.Models.User {
Username = dbUser.EmailAddess,
Password = "*****"
};
LoginApi.UserSession apiUserSession = await LoginApi.Login(apiUser);
var vm = new ViewModels.User(apiUserSession.User.Details);
return View(vm);
Note how the class names are all User, but in different namespaces. Quoting PEP-20: Zen of Python:
Namespaces are one honking great idea -- let's do more of those!
Hope this helps
Is it possible to change to using an interface?
Perhaps you could create an IColorScheme interface that all of the classes implement?
This would work well with the factory pattern as shown by Chris Marasti-Georg
It's a very late partial answer - but if you define the same class 'ColorScheme', in the same namespace 'Outlook', but in separate assemblies, one called Outlook2003 and the other Outlook2007, then all you need to do is reference the appropriate assembly.
The best way I've found to simulate alias in C# is inheritance.
Create a new class that inherits from the original class:
public class LongClassNameOrOneThatContainsVersionsOrDomainSpecificName
{
...
}
public class MyName
: LongClassNameOrOneThatContainsVersionOrDomainSpecificName
{
}
The only thing that you would need to be careful is the constructor. You need to provide a a constructor for MyName class.
public class MyName
: LongClassNameOrOneThatContainsVersionOrDomainSpecificName
{
public MyName(T1 param1, T2 param2) : base(param1, param2) {}
}
In this example I'm using T1 and T2 as generic types, since I don't know the constructor for your LongClassNameOrOneThatContainsVersionOrDomainSpecificName class.
Beware, though, that this is not alias. Doing this to you application might run into some issues or problems. You might need to create some extra code to check for types, or even overload some operators.

Can we create class with name "class"?

Lets forgot about why I need this.
Can we create a class with name "class".
Below code resulted in compilation error as class is a reserve keyword.
public class class
{
}
so is there any hack or a way to fool C# compiler? :)
This Question was asked by interviewer in my last interview and he told me it is possible.
You could use:
public class #class
{
}
But why do you want that?
C# Keywords
Keywords are predefined, reserved identifiers that have special
meanings to the compiler. They cannot be used as identifiers in your
program unless they include # as a prefix. For example, #if is a valid
identifier but if is not because if is a keyword.
What i've learned from this answer was that new key-words won't be added globally but only as contextual key-words to avoid breaking programs written in earlier versions. You find a list in the link above.
So interestingly enough this is valid(better: compiling) code:
public class var
{
public void foo()
{
var var = new var();
}
}
Here's another one:
public class dynamic
{
public void foo()
{
dynamic dynamic = new dynamic();
}
}
But never do this. It will break your other code where you've used var or dynamic before.
Yet another alternative is through Unicode
using System;
public class Program
{
public static void Main()
{
cl\u0061ss a = new cl\u0061ss();
Console.WriteLine(a.GetType().Name);
}
}
public class cl\u0061ss
{
}
Note: Console.WriteLine() will print class
DotNetFiddle link is here.
Most programmers use underscore '_' at the beginning of the name of a variable or whatsoever if it is a reserved word e.g.
public class _class
{
}
variable declarations example
int _int;

c# Naming Convention

Im starting a new project and i have some problem trying to implement some naming conventions.
I used to work with Classes starting with Uppercase and Singular, like Car or User, and my variables starting with lower case, so if I needed to declare a class that had some variables of type Car and User i would do it like this:
public Car car;
private User user;
Now im trying to use some properties and as i see they should also be PascalCase , wich mean if i need to declare the same examples i would be:
public Car Car { get; set; }
private User User { get; set; }
And you can all see what would the problem be here, or you don't see it as a problem?
So what should i do? what am i missing here?
The C# naming convention recommends everything that is public as well as classes, interfaces etc., to start with an uppercase letter. The rest should start lower case.
There is no problem with:
private User User { get; set; }
... since the position of each name (word) defines what is what.
The English language works the same way.
e.g.: "I love love." (pronoun, verb, noun)
What you're run into is called the Color Color problem, because the most common way it crops up is "I need a property called Color of a type called Color". C# has been specifically designed to manage Color Color situations elegantly.
For details, read section 7.6.4.1 "Identical simple names and type names" in the C# 4 specification.
The rules for Color Color situations are a bit complicated (believe me, they do not make the compiler implementer's life any easier!) and they can lead to some interesting corner cases. If this subject interests you then you should read my article on it:
http://blogs.msdn.com/b/ericlippert/archive/2009/07/06/color-color.aspx
I think in many cases the context means you'd have a specific name - e.g. Car customersCar, etc.
Saying that, many people don't have an issue with the name/type being the same - see this link:
Should a property have the same name as its type?
For naming conventions in general, following MS isn't a bad start -
http://msdn.microsoft.com/en-gb/library/vstudio/ms229045(v=vs.100).aspx
There is no issue here; As #NDJ suggested you can apply context to add additional prefix to the property if you do not feel comfortable; but this will not generally add additional meaning to the context.
As a general Microsoft style guide encourages the use of Pascal Case for properties.
For a more complete guide on capitalization see the following MSDN article
There is no problem there.
Because in the context where you would use the class it can not be misstaken for the property and vice versa.
Edit: Ok, Im going to assume you have the Userclass inside the carclass like this:
public class Car
{
private class User
{
}
private User User
{
get;
set;
}
}
Which indeed would create problems. Move out your user and the problem is solved.
public class Car
{
private User User
{
get;
set;
}
}
public class User
{
}
Barring the internal class problem that #Evelie pointed out you should not have any issue naming a property the same as the type - in fact this is not an uncommon practice. .NET has public Color Color properties all over the place.
As the following program illustrates the compiler can distinguich between instance calls and static calls:
void Main()
{
Car c = new Car();
c.Test();
}
public class Car
{
public Car()
{
User = new User();
}
public void Test()
{
User.Static(); // calls static method
User.Instance(); // implies this.User
}
public User User { get; set; }
}
// Define other methods and classes here
public class User
{
public static void Static()
{
Console.WriteLine("Static");
}
public void Instance()
{
Console.WriteLine("Instance");
}
}

C# - Call Method in Base Class

I have 2 classes:
public class A
{
public void WriteLine(string toWrite) { Console.WriteLine(toWrite); }
}
public class B : A
{
public new void WriteLine(string toWrite) { Console.WriteLine(toWrite + " from B"); }
}
In my code I do the following:
B writeClass = new B();
writeClass.WriteLine("Output"); // I expect to see 'Output from B'
A otherClass = (A)writeClass;
otherClass.WriteLine("Output"); // I expect to see just 'Output'
I presumed this would work because of polymorphism.
However, it always writes 'Output from B' every time. Is there anyway to get this to work the way I want it to?
EDIT Fixing code example.
When you "hide" a method from the base class using NEW you are just hiding it, thats it. It's still called when you explicitily call the base class implementation.
A doesnt contain WriteLine so you need to fix that. When I fixed it I got
Output from B
Output
namespace ConsoleApplication11
{
class Program
{
static void Main(string[] args)
{
B writeClass = new B();
writeClass.WriteLine("Output"); // I expect to see 'Output from B'
A otherClass = (A)writeClass;
otherClass.WriteLine("Output"); // I expect to see just 'Output'
Console.ReadKey();
}
}
public class A
{
public void WriteLine(string toWrite) { Console.WriteLine(toWrite); }
}
public class B : A
{
public new void WriteLine(string toWrite) { Console.WriteLine(toWrite + " from B"); }
}
}
Your method on class A is Write, not WriteLine. Change it to the same name and it will work as you expect. I just tried it and get:
Output from B
Output
Polymorphism (C# Programming Guide) explains this quite well. (This is the newer version of the original poster's link.) The page shows examples where a derived class overrides a virtual member and where new members hide base class members.
There appears to be some confusion over the new modifier. From the documentation:
Although you can hide members without the use of the new modifier, the
result is a warning. If you use new to explicitly hide a member, it
suppresses this warning and documents the fact that the derived
version is intended as a replacement.
Note that the hidden member does not need to be virtual.
Best practices:
Strongly prefer overriding to hiding. Polymorphic calls are idiomatic in OO languages.
If you intend to hide a member, always use the new modifier.
Never release code with compiler warnings.
If every developer on your team agrees that a compiler warning cannot be fixed, suppress it.
Don't use new keyword when you override the method in class B. And declare the method in A as virtual.
The 'new' keyword is making B's implementation of WriteLine overwrite A's implementation.
Don't accept this as an answer, but in my experience, it's almost always a mistake to use the 'new' keyword in this fashion. It's less readable and muddy's the clarity of your code.
Your class A has a Write function instead of WriteLine
public class A
{
public virtual void WriteLine(string toWrite) { Console.WriteLine(toWrite); }
}
public class B : A
{
public override void WriteLine(string toWrite) { Console.WriteLine(toWrite + " from B"); }
}
First: I guess you wanted to name the methods both "WriteLine" but the one in class A is only named "Write". And second: yes you inherit B from A but the object will still be of type "B" so now I don't think what you want is possible.

Categories