Can I duplicate an enum into another namespace in c#? - c#

Suppose I'm making a utils library, and among other things I have in it a class that involves key input:
public class KeyInput {
...
public bool IsKeyPressed(Keys key) {
// determine and return whether that key is pressed
}
...
}
The Keys enum is in the standard library, but I'm attempting to make this library so that the user doesn't have to even touch anything outside of it, including the standard library if I can (or at least not to do anything that these utils are intended for). I can use Enum.TryParse() and have the user put in a string according to the what key they want, but it would be much more preferable if I could actually have an enum for it. What I really want is a duplicate of System.Windows.Forms.Keys that has an implicit conversion to it, or alternately some way to make it so that whenever someone uses my namespace, it includes the System.Windows.Forms.Keys enum. Is there any way to do this (or something effectively the same)?

I can't comment yet, so putting this in here.
I understand why you wish to have it in your class/namespace code, so that when someone uses it, they do not have to include any other usings.
Check whether to have an include or using statement inside your namespace, see the differences here: Should 'using' statements be inside or outside the namespace?
Maybe include all functions for the conversion in this class so that if the end user needs to use it, all the functions are handled inside your class.
A couple of options:
So put in all your conversions and functionality that a user could require inside the class, using it almost like a wrapper. Thus defeating the need for the user to include another library.
Have the class output the enum, then if a user uses var output = className.func(); they should not need to include the library.

Related

How to structure classes in a C# program

I have a VSTO (Excel) project written in C#. Three questions:
I have a lot of variables that are populated once and then referenced extensively throughout the project. So I created a public static class which I called "Omni" - since that is both descriptive and short. Is something like this the recommended approach?
I put common functions in a public static class that I named "Utilities". I then used the "this" keyword as the first parameter, making them extension methods. They can then be accessed from anywhere - without using a "Utilities." prefix (although I'm not exactly sure why). Same question: is this the preferred way of doing this?
Finally, I have some common 'subroutines', i.e., public void methods. So parameters are passed in and processed, but nothing is returned. Should such common code just go in its own appropriately named public static class and then get called with the class name as a prefix? If so, is there any convention as to what the name of the class would be?
I realize these are newbie type questions (and I have been searching for a while!). Thanks.
Regarding your points
I have a lot of variables that are populated once and then referenced
extensively throughout the project. So I created a public static class
which I called "Omni" - since that is both descriptive and short. Is
something like this the recommended approach?
Yes, it is common practise to centralize for example string constants that
are often used.
If you have more of those, I would start to structure those to different
classes.
If you want that to be flexible and e.g. have cases where there are
mappings between constants, like Green = 1, I would move to some
enumeration value technology.
More on that idea can be found in this article
If the value does not change between different starts of your application,
check if you can use resources for that, which is often a good choice
for string constants to.
I put common functions in a public static class that I named
"Utilities". I then used the "this" keyword as the first parameter,
making them extension methods. They can then be accessed from
anywhere - without using a "Utilities." prefix (although I'm not
exactly sure why). Same question: is this the preferred way of doing
this?
Extension methods are a handy way of getting things like conversions done.
Just do not everything as an extension, just conversions as a rule of thumb.
Finally, I have some common 'subroutines', i.e., public void methods.
So parameters are passed in and processed, but nothing is returned.
Should such common code just go in its own appropriately named public
static class and then get called with the class name as a prefix? If
so, is there any convention as to what the name of the class would be?
This, in opposite of the others, looks like a design flaw.
Perhaps you can provide more information on what those subroutines do.
In object oriented code, code is distributed near the objects it is working
with. If you depend heavily on code that is in static classes, probably there
is something wrong. Do your static classes have members? Do they share some
knowledge between different calls to your static classes?

C# namespaces: how to follow standards without causing annoying conflicts?

I'm working on a C# library (let's just call it "Foo" for the sake of this question). It has some needs very similar to standard .NET needs: for example, it provides some drawing services, and some conversion services.
For the sake of familiarity and users of the library being able to guess what things are called, I'd like to follow the .NET standard, and name these parts of the library Foo.Drawing and Foo.Convert (and so on). But I'm finding that in actual use, this causes pain. People almost always have "using System;" at the top of each file, and when using this library, they want to have "using Foo;" as well. But now they have two Drawing and two Convert modules, and hilarity ensues.
For example, now instead of just using Drawing.Color for a parameter or variable type, you have to explicitly spell out System.Drawing.Color, or the compiler complains that Foo.Drawing doesn't have a Color type. Similarly, you want to use a standard Convert.ToInt32, you have to say System.Convert.ToInt32, even though you're already using System, because otherwise it finds Foo.Convert and fails to find ToInt32.
I understand why all this is as it is, but I'm still new to the C# community, so I don't know which is the most standard solution:
Leave it this way, and expect users to use fully-qualified names where necessary?
Rename the conflicting modules to something else (maybe Foo.Graphics instead of Foo.Drawing, and Foo.Conversion instead of Foo.Convert)?
Use some prefix on the standard names (Foo.FDrawing and Foo.FConvert)?
Something else?
Any advice from you more experienced C# gurus will be appreciated!
You can use namespace aliasing :
using System;
using FConvert = Foo.Convert;
public class Bar
{
public void Test()
{
var a = Convert.ToInt32("1");
var b = FConvert.ToInt32("1");
}
}
One of the main usage of namespaces is to avoid name clashing.
It means that namespaces allow developers to create types with identical names, as long as the belong to different namespaces.
A library usually have at least a root namespace, and possibly nested namespaces that logically groups the related types.
Name your types as you wish, as long as the names are meaningful and represent what the type really are. A client of your library expects a type named Animal to represent an Animal, not something else. The same applies for naming namespaces.
However, avoid at all cost the names from System, since it will be really annoying for your library clients (as you described) to deal with conflicting names all over the place.
A common way to deal with conflicting namesapces inside a class is to use namespace aliasing:
using FooConvert = Foo.Convert;
using BarConvert = Bar.Convert;

Reusable Class Library Implementation

I've built a reusable Class Library to encapsulate my Authentication logic. I want to be able to reuse the compiled *.dll across multiple projects.
What I've got works. But, something about how I'm making the reference, or how my Class Library is structured isn't quite right. And I need your help to figure out what I'm doing-wrong/not-understanding...
I've got a Class Library (Authentication.dll) which is structured like this:
namespace AUTHENTICATION
{
public static class authentication
{
public static Boolean Authenticate(long UserID, long AppID) {...}
//...More Static Methods...//
}
}
In my dependent project I've added a reference to Authentication.dll, and I've added a using directive...
using AUTHENTICATION;
With this structure I can call my Authenticate method, from my dependent project, like so...
authentication.Authenticate(1,1)
I'd like to be able to not have to include that "authentication." before all calls to methods from this Class Library. Is that possible? If so, what changes do I need to make to my Class Library, or how I'm implementing it in my dependent project?
In C# a function cannot exist without a class. So you always need to define something for it, being a class for a static method or an object for an object method.
The only option to achieve that would be to declare a base class in the Authentication assembly from which you inherit in the dependent projects.
You could expose Authenticate as a protected method (or public works too), and call it without specifying the class name.
public class MyClassInDependentProject : authentication
{
public void DoSomething(int userId, long appId)
{
var success = Authenticate(userId, appId);
…
}
}
That said, you'll quickly find this to be a bad design. It conflates a cross-cutting concern with all sorts of other classes, and those classes are now precluded from inheriting from any other class.
Composition is a core principle of object-oriented programming, and we have the idiom "Favor composition over inheritance." This simply means that we break down complexity into manageable chunks (classes, which become instantiated as objects), and then compose those objects together to handle complex processing. So, you have encapsulated some aspect of authentication in your class, and you provide that to other classes compositionally so they can use it for authentication. Thinking about it as an object with which you can do something helps, conceptually.
As an analogy, think about needing to drill a hole in the top of your desk. You bring a drill (object) into your office (class). At that point, it wouldn't make sense to simply say "On," because "On" could be handled by your fan, your lamp, your PC, etc. (other objects in your class). You need to specify, "Drill On."
If you are making a class library in C# you should learn to use the naming conventions that exists: Design Guidelines for Developing Class Libraries
Here is how you should name namespaces: https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/interface
C# is also an object oriented language, hence the need of classes (using Authentication as you should name your class).
It also seems like the data source is hard coded. Your class library users (even if it's just you) might want to configure the data source.
Google about singleton and why it's considered to be an anti pattern today (in most cases).
You are obliged to use Class in order to invoke your method, just
When is static class just NameClass.Method
When is not static, you must create instance, ClassName ob = new ClassName(); ob.Method();
The format of a call like this is class.method, and you really can't escape using the "class" moniker even with the "using" designation. Something has to "host" the function.
I don't think what you are asking for is possible without using the base class method Jay mentioned. If all you want is to simplify the syntax whenever you call Authenticate() however, this silly solution (adding an extra method in each class that needs to do authentication) may be just what you want:
private static void DoAuth(long UserID, long AppID){
authentication.Authenticate(UserID, AppID)
}
If the ID's are always the same within some context, you could also overload it:
private static void DoAuth(){
DoAuth(1,1)
}
Yes, this does mean you have to add more code wherever you want to do the authentication (that's why it's silly! ;) ). It does also however, also reduce this:
authentication.Authenticate(1,1);
...into this:
DoAuth();
I leave the cost / benefit analysis of this up to you..
I know I am some 3 years late but here goes nothing.
To keep your code cleaner and more readable you should create a new namespace for all the re-usable code that you want to have. Then in that namespace have the Authentication Class and Authenticate Function.
To use this you can easily set a using on your namespace and use the function as you are doing like
Authentication.Authenticate()
But to use
Authenticate()
by itself you can always do
using MyNamespace.Authentication;
and in your code use Authenticate Function directly.

What hack can I use to define a C# property with same name as class?

I'm using C# to make a .Net class library (a DLL) that will be distributed widely. I have an abstract class called Value, and I want it to have an abstract double property that is also called Value i.e.
public abstract class Value {
// Only accessible by subclasses within the project.
internal Value() {}
public abstract double Value {
get;
}
}
But the C# compiler won't allow this - I get the message "member names cannot be the same as their enclosing type", as discussed here.
I understand that the easiest thing to do would be to change the name of the property or the name of the class... But really I want the names to be like that, and I'm quite happy to implement an ugly hack to get it that way. So long as it works properly from external code that uses this DLL.
Unlike C#, VB.Net will allow me to define a property with the same name as the class, so I'm currently investigating merging my C# project with a VB project that defines the Value class (and its Value property) to make one DLL. This doesn't seem to be quite as straightforward as I was hoping.
Another option would be to re-write the whole project in VB... Not very appealing, but I'll consider it if necessary. I prefer C# over VB.Net but my priority is to get the built DLL the way I want it.
I'm wondering what other alternatives there might be. Any ideas for a good way to hack this?
EDIT: From the comments below it's clear that quite a number of people don't think much of the name "Value" for a class... Could anyone explain why it's so bad? I know it's not very descriptive, but I think it fits well in the context of my project. Is it because it's a keyword in C# that's used in property setters?
You cannot do that directly. You could, however, consider:
impelenting an interface with a Value member, and using explicit interface implementation (callers would have the use the interface, though)
renaming it in the class, and using an extension method to expose a Value() method, so obj.Value() works
rename it in the class, but expose it as Value in the subclasses
Ugly hack:
public abstract class ValueBase {
public abstract double Value { get; }
internal ValueBase() {}
}
public abstract class Value : ValueBase {
internal Value() {}
}
public sealed class ValueReal : Value {
public override double Value { get { return 123; } }
}
If your class is representative of a double (except for some additional metadata), you could opt for a conversion operator:
public abstract class Value
{
protected abstract double GetValue();
public static explicit operator double (Value value)
{
return value.GetValue();
}
}
Then your client code could access the metadata or cast an instance of type Value to a double. Depending on the metadata and usage, you might make the conversion implicit so you don't have to do an explicit cast, and you might define a conversion from double to Value.
There is a similar approach used by the System.Xml.Linq assembly where, for example, XElement can be cast to any primitive type as a means of accessing its "value".
As other people have said, this is not possible in C#.
Other people have criticised the name Value as a class, and while I agree it's likely too generic, I can see situations where it may make sense.
Bearing that in mind, if Value is an abstract class, perhaps ValueBase might be a decent, conformant, name? Much of the .Net framework (particularly WPF) uses XxxBase.
Another option to consider is prefixing the class name with the name of your project, as in FooValue.
Value is a terrible name for a class. It's extremely vague, so it does nothing to describe what a Value represents, and it clashes with the reserved word 'value'. You will find yourself using value = Value.Value, wondering why your code makes no sense, and eventually trying to fix a hideous bug that is a direct result of using 'value' instead of Value or value or _value or this.value. And what happens when you have to store another kind of arbitrary number? Will you call it Value2?
Name the class with a more specific and meaningful name and the problem will no longer exist. Don't fix the symptoms - fix the cause.
Even if you only rename it to "DataValue" or 'MySystemValue', you will be doing yourself a great service.
Bowing to popular opinion, I've decided to rename my Value class to DataValue. I'm pretty happy with that name, and it means I don't need any hacks to have the property called Value. So thank you very much to everyone for the feedback.
But, despite the useful answers, I still don't think the question has been answered ideally. None of the proposed solutions do exactly what was asked for, or at least not without side effects like the requirement for an otherwise-superfluous interface or public class. I should probably have been clearer in my question that I was perfectly happy to consider a hack that involved unsafe code, or modification of intermediate language or some such, as my priority was to get the public API of the DLL the way I wanted it, irrespective of whatever messy hacks might lurk hidden within it's source.
So here's the best solution that I could come up with. I haven't actually done it myself (no need now I'm using a different name for the class), but I don't have any reason to suspect that it won't work:
In the solution that contains your C# class-library project, add a new VB class-library project.
In the VB project, create the class (Value in my original example). In VB you'll have no problems adding a property with the same name as the class.
If your VB class has internal methods that need to be referenced by your C# code, reference the C# assembly using InternalsVisibleTo in your VB class.
You should now be able to reference your VB class from your C# project. But when you build the solution you'll get two separate DLLs: one for the C# code and one for the VB code. It looks like the ILMerge tool makes it very straightforward to merge the two DLLs into one (just one call from the command line).
So finally you should have a single DLL that contains the class with the property of the same name, and all the code in your C# project. Other projects that use that DLL (C#, VB, or any other .Net language) should not see your hacky effort - all they'll see is a coherent API with no superfluous public classes or interfaces.

WM_SETFOCUS, where defined for C#?

I need to find out where WM_SETFOCUS is defined.
For instance, I know it isn't System.Windows.Forms.WM_SETFOCUS
I've looked online, and everything seems to just use the name with no mention of how to let your compiler know the name.
I DO know the integer value it represents, but I really want to reference an authoritative assembly, and not just litter my code with constants.
I am using the value in a class which implements IMessageFilter.
ADDED DETAILS:
Using IMessageFilter,
I am getting messages, and the messages have a Msg field (int) which identifies its type. Where can I find C# definitions of those integer values? (I don't need one named WM_SETFOCUS, I just need something with all the definitions of the values I am receiving.)
Since Microsoft supplies IMessageFilter, shouldn't they also supply the information needed to make it useful?
It would seem to be defined in System.Windows.Forms.NativeMethods.WM_SETFOCUS (Which, unfortunately is an internal class). It's also defined in Microsoft.VisualStudio.NativeMethods.WM_SETFOCUS
If you're worried about littering your code with native methods, I would do as the framework does and create an internal NativeMethods static class, and dump everything interop-related in it. At least you can keep it all in one place.

Categories