I want to create a custom method that will work when added after “Console” in c#. It would be sort of similar to Console.WriteLine().
It would look something like this: Console.PrintMyName(). And when it is called, it would do this: Console.WriteLine(“James”).
Is there some way to do this by defining a function that only works as a method when put after after “Console”.
In short, no.
The closest thing you can do is approximate what you want.
The Console class (System.Console specifically) is a static class and so cannot have "methods added to it" in the same way as a class that can be instantiated (instantiated classes can have extension methods).
The closest you can come to this is to either
create your own class named Console with it's own PrintMyName method. However, if you use both System.Console and your custom MyCustom.Console in the same compilation unit, you will have to disambiguate them by addressing one or both by their full namespace.
create a new static class with a completely different name.
Related
Is it possible to define a compiler constant on a PER-FILE/project-item basis ?
Background:
I want to achieve a Database Abstraction Layer (DAL), that separates all read, and write tasks, but retain a DAL that can do both, but without implementing the same methods multiple times (abstract class means there will be 1 instance class for every supported database type).
So I want to separate my DAL like this:
abstract class ReadDAL
abstract class WriteDAL
abstract class ReadWriteDAL (multiple-inheritance from Read&Write-DAL).
Unfortunately, that doesn't work, because C# doesn't support multiple inheritance.
So one way around this problem would be by defining interfaces:
abstract class ReadDAL : IReadDAL
abstract class WriteDAL : IWriteDAL
abstract class ReadWriteDAL : IReadDAL, IWriteDAL
However, if I do this, I'll have to change the interface definition every time I change a method in one of the DALs, and change the methods defined in ReadWriteDAL, and I have to copy-paste somewhere the method implementation, which means there will be a DRY-noncompliance mess.
I figured what I could do was adding the same file a second time as link, and having a define on a per-project-item basis:
#if SOMECONSTANT // true if file is PartialReadDAL.cs
public partial abstract class ReadDAL
#else // false if "file" is link called "PartialReadWriteDAL.cs" symlinking to PartialReadDAL.cs
public partial abstract class ReadWriteDAL
#endif
and here some implementation.
But can I somehow define a compiler constant per file ?
Or achieve a similar effect somehow ?
The symlink route would be very, very confusing. When forced into doing this, I would implement that by prepending some #defines into relevant files as a prebuild step. Then I would #if on presence of these symbols in the code. I wouldn't like this at all though: my guess is that this would not be as transparent as I would like even if I cleared this markers after build's end so it won't get in version control.
Is ReadWriteDAL going to contain some state of it's own, or is it going to be just a dispatcher for method calls into ReadDAL and WriteDAL? If it's just a dispatcher, you might consider to drop actual implementation (ReadWriteDAL) and pass calls to IReadDAL and IWriteDAL as registered in composition root, using dynamic proxy mechanism. I wrote a tool like that for Castle Windsor.
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?
In working on a C# XNA project I've created quite a few methods to minimize code in the default LoadContent/Update/Draw methods. I am wondering if it is possible to move those methods out of the Game1.cs file into another source file without encapsulating them in a new class and passing object references?
I've tried creating a new .CS file with the proper using statements and namespace declaration, but the compiler tells me that it is missing a class declaration so I don't believe I am doing it right. Currently I've created a HelperMethod class that I instantiate at the top of the Game1.cs file, but it would be nice to be able to use something like an include_once from PHP in C#.
Is there a way to create a method or function file and include it in my code, or should I stick with the HelperMethod class?
No you can't.
All methods in C# must be inside an object.
You're thinking about it all wrong if you're worried about passing references around. References are light weight.. and you've just smacked head first into Premature Optimization.
You could also use partial classes to break a class definition across multiple files. See this article on MSDN for more information: Partial Classes and Methods (C# Programming Guide) http://msdn.microsoft.com/en-us/library/wa80x488.aspx
After reading this:
Equivalent to PHP's include in C#
it would appear that the best course of action is to stay with the helper class that I have currently in place. It doesn't appear that compiled languages make use of any sort of include function that would just append code to the current file.
+1 on STLDeveloper's suggestion on using Partial Classes and Methods.
Additional idea: if it makes sense for what you're trying to accomplish (especially if your code may be reusable in other XNA Game projects you might have), create your own Game class that extends Microsoft.Xna.Framework.Game and have Game1 inherit from that. That would include the methods you've written in a separate .cs file but keep your Game1.cs "smaller".
Game.cs:
public class Game : Microsoft.Xna.Framework.Game
{
/* Your methods here */
}
Game1.cs:
public class Game1 : Game
{
/* More of your methods here */
}
Maybe you are looking for extension methods?
Extension Methods
Or you can try keeping a class that houses delegates.
Delegates
I have a 3rd party class library. One of the classes in that library, has a constructor with multiple overrides.
I want to tell Unity to create the class, using a constructor with fewer parameters (by default, it selects the one with the most number of parameters). How can I do this?
I know I can use InjectionFactory, but I prefer to let Unity create the object for me, than writing a delegate for it. Also if I had access to the source I could probably label the desired constructor with InjectionConstructor, but I don't. So what would be my other option?
Since you cannot use InjectionConstructorAttribute (as you mentioned, the library is not yours), you can use the InjectionConstructor class (not an attribute). You will need to call Resolve yourself to make sure Unity builds up the constructor parameters. Something like this:
IUnityContainer c = new UnityContainer()
.RegisterType<IStuff, GoodStuff>()
.RegisterType<StuffUser>(new InjectionConstructor(c.Resolve<IStuff>()));
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.