I have a number of classes in a Classes file, and I want them all to be able to access the same, global method to save duplicating code. Problem is, I can't seem to access a method from another class in my file - any ideas?
So my class1.cs layout is similar to this:
public class Job1
{
public Job1()
{
}
}
public class Methods
{
public static void Method1()
{
//Want to access method here from Job1
}
}
You'll need to specify the class they are in. Like this:
public Job1()
{
Methods.Method1()
}
If the class Job1 is in a different namespace from Methods then you'll need to either add a using clause, or specify the the namespace when calling the method. Name.Space.Methods.Method1()
Actually. Public Job1(){} is a constructor and not a method. It can be called from main class by creating object form the JOB1 class. Here add the following code:
public static void method1()
{
Job1 j1=new Job1();
}
constructor can be invoked by creating a object to the corressponding class....
To access methods of other classes, the methods must be static with a public Access modifier.
static - Not bound to an instance of the class but shared by all other instances.
private - data can only be accessed from inside the same class.
public - data can be accessed from other classes but must be referenced.
Related
I have a class and a method inside it. I want to use two different attributes.
[TokenValidate]
public class Auth
{
[NoTokenValidate]
Public void methodname()
{
}
}
I want that to disallow one particular method to use the parent class attribute. Is it possible?
I have the following class:
class Base<T> where T : Base<T>
{
protected static string Source;
public static List<T> Read()
{
return GetResource(Source);
}
}
I want this class as baseclass for its functionality but every derived class has to have a different Source. My problem is that I can't assure the Source is set before Read is called. I know I could ask if the Source is set before GetResource is called but that's not the point. I need it to be set before any static member of my class is called.
Generic parameters can't have static Members so I can't take it from there.
I tried setting the Source in the derived class's static constructor but that will only be called when I call a member that is in the derived class and not in the Base.
I tried using a overridable method inside of the static Base constructor but such a method has to be static as well and static methods can't be overwritten.
When I set the Source manually, there is a chance that the Read-Function has already been called, so I have to set the Source before it can be called.
I know I could give Source as a parameter in Read but I want Read to be used without parameters.
Is there any way I can assure that the Source is Set before any other Member of my class is called, so that any dependent code is inside the derived class and doesn't have to be called by anyone using a derived class?
I basically want it to work like this:
class Derived : Base<Derived>
{
// somehow set Source
Source = "This is my source";
}
class User
{
private List<Derived> MyResources;
public User()
{
MyResources = Derived.Read();
}
}
Note: the Source is basically a SQL statement so an Attribute or something like that wont be sufficient I think.
Ok, I found an answer. It is not as pretty as I hoped it would be but its the best I could come up with.
I will use an interface to force an Instance of T to have a certain method that provides my source.
interface ISource
{
string GetSource();
}
I then implement that into my base class as such:
class Base<T> where T : Base<T>, ISource, new()
{
public static List<T> Read()
{
// here I create an Instance to be able to call the Methods of T
string source = (new T()).GetSource();
return GetResource(source);
}
}
The derived class:
class Derived : Base<Derived>, ISource
{
public string GetSource()
{
return "This specific source";
}
}
Usage as such:
class User
{
public User()
{
List<Derived> myResources = Derived.Read();
}
}
This of course will lead to every instance of Derived having the GetSource-method but for my scenario thats not a big deal.
Also, since it creates an instance in the Read-method, this could be time consuming depending on the constructor of Derived. In my scenario it only has the standard constructor.
So use with caution.
I have a class defined as:
public class DatabaseEntity<T> where T : DatabaseEntity<T> {
public static string Query { get; protected set; }
public static IList<T> Load() {
return Database.Get(Query);
}
}
public class Node : DatabaseEntity<Node> {
static Node() {
Node.Query = #"SELECT Id FROM Node";
}
}
When I run Node.Load() from a codebehind (Window.xaml.cs) the Node's static constructor never fires; or at least doesn't hit a breakpoint and does not set Node.Query to anything other than null.
Is there any reason why this might occur?
Solution
Check out the answers below for a few solutions. For my case, I decided to simply make the Query variable public, and set all instances of Query in one place. (Not ideal, but it works.)
The problem lies in your assumptions about when a static constructor is called. The documentation, which isn't the clearest, states that
It is called automatically before the first instance is created or any static members are referenced.
You may assume that if you call
Node.Load();
that you are calling a static method on the Node class, but in fact you're calling it on the base class, as that is where it is implemented.
So, to fix this, you have two choices. First, you can trigger the static constructor explicitly by creating a new instance of the Node class prior to calling Load()
var foo = new Node(); // static ctor triggered
Node.Load();
or create a protected virtual member that the base class can call in order to get the query value (can't use abstract here, unfortunately)
public class DatabaseEntity<T> where T : Derp {
protected abstract string Query { get; }
public static IList<T> Load() {
return Database.Get(new DatabaseEntity<T>().Query);
}
}
Both of which are hacky. Better to dispense with the statics altogether and go with instance methods. Statics should be used sparingly, as they result in tight coupling and other design headaches such as this.
Yes, static constructors will not be called till the members of the class is first accessed or first instance is created.
In your case you're accessing DatabaseEntity<T>.Load, so static constructor of DatabaseEntity<T> will be called not its derived class ones.
Even though you call Node.Load it is mapped to DatabaseEntity<Node> at compile time. So technically you're not accessing Node class at all.
You can also call class constructors directly using System.Runtime.CompilerServices and the RuntimeHelpers type by doing something as follows:
RuntimeHelpers.RunClassConstructor(type.TypeHandle);
So for example you could use reflection to loop over all types in an inheritance chain and call each of the static constructors.
Here is a piece of code:
private class myClass
{
public static void Main()
{
}
}
'or'
private class myClass
{
public void method()
{
}
}
I know, first one will not work. And second one will.
But why first is not working? Is there any specific reason for it?
Actually looking for a solution in this perspective, thats why made it bold. Sorry
It would be meaningful in this scenario; you have a public class SomeClass, inside which you want to encapsulate some functionality that is only relevant to SomeClass. You could do this by declaring a private class (SomePrivateClass in my example) within SomeClass, as shown below.
public class SomeClass
{
private class SomePrivateClass
{
public void DoSomething()
{
}
}
// Only SomeClass has access to SomePrivateClass,
// and can access its public methods, properties etc
}
This holds true regardless of whether SomePrivateClass is static, or contains public static methods.
I would call this a nested class, and it is explored in another StackOverflow thread.
Richard Ev gave a use case of access inside a nested classes. Another use case for nested classes is private implementation of a public interface:
public class MySpecialCollection<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
return new MySpecialEnumerator(...);
}
private class MySpecialEnumerator : IEnumerator<T>
{
public bool MoveNext() { ... }
public T Current
{
get { return ...; }
}
// etc...
}
}
This allows one to provide a private (or protected or internal) implementation of a public interface or base class. The consumer need not know nor care about the concrete implementation. This can also be done without nested classes by having the MySpecialEnumerator class be internal, as you cannot have non-nested private classes.
The BCL uses non-public implementations extensively. For example, objects returned by LINQ operators are non-public classes that implement IEnumerable<T>.
This code is syntactically correct. But the big question is: is it useful, or at least usable in the context where you want to use it? Probably not, since the Main method must be in a public class.
Main() method is where application execution begin, so the reason you cannot compile your first class (with public static void Main()) is because you already have Main method somewhere else in your application. The compiler don't know where to begin execute your application.
Your application must have only one Main method to compile with default behavior otherwise you need to add /main option when you compile it.
When should I prefer either a static or a normal class? Or: what is the difference between them?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace staticmethodlar
{
class Program
{
static void Main(string[] args)
{
SinifA.method1();
}
}
static class SinifA
{
public static void method1()
{
Console.WriteLine("Deneme1");
}
}
public static class SinifB
{
public static void method2()
{
Console.WriteLine("Deneme2");
}
}
public class sinifC
{
public void method3()
{
Console.WriteLine("Deneme3");
}
}
public class sinifD : sinifC
{
void method4()
{
Console.WriteLine("Deneme4");
}
sinifC sinifc = new sinifC(); // I need to use it :)
}
}
Static classes contain static objects that can't be instantiated multiple times. Usually what I use static classes for are to house static methods that provide calculations, general processing patterns, string output formats, etc. Static classes are light weight and don't need instantiation.
For instance System.IO.File is a static class with static a method Exists(). You don't create a File object to call it. You invoke it like this
System.IO.File.Exists(filePath)
Rather than doing this
System.IO.File myFile = new System.IO.File(filePath);
if(myFile.Exists())
{ /* do work */ }
If you require several objects in software, then you use dynamic classes. For instance if you have an inventory system you may have several Product objects and in that case you would use a dynamic class such as this
public class Product
{
public int ProductID { get; private set; }
public string ProductName { get; private set; }
public int Qty { get; set; }
public Product( int productID, string productName, int total )
{
this.ProductID = productID;
this.ProductName = productName;
this.Qty = total;
}
}
static classes cannot be instantiated or inherited.
static classes are marked as sealed and abstract by compiler in the output MSIL.
all members of static classes must be static as well.
only static classes can host extension methods.
static classes cannot be used as generic type arguments.
You can create instances of "normal" classes via the class constructor.
var normal = new Normal();
You cannot create instances of static classes. They can only have static methods.
Also worth noting is that you must declare extension methods in static classes.
From the MSDN documentation on static classes:
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
In simple terms:
A static class cannot be instantiated using the new keyword.
All methods in a static class must be static and can be called directly without instantiation.
A "normal" class MUST be instantiated however any static methods in a "normal" class can be called without instantiation.
Non static methods in a "normal" class cannot be called without first instantiating the containing class.
Static members can be called without using an instance of the class. For example, a static Math class with an Area method call be called by Math.Area without instantiating the Math class first.
A normal class is one which you can instantiate and can use with objects.
A static class is one which can not be instansiated and can't be extended.
That means a static class is sealed and abstract by default, you may look at the
MSIL of a static class compiler puts sealed and abstract in front of a static class.
So, because a static class can't be instantiated, you can't have instance methods defined
on static classes, so all methods must be static and public ofcourse as you would want to
use them.
A static class is singleton by default.
Static classes are used for defining extension methods because you don't want to
instansiate them.
Static classes are like global provider of unique services.
I hope that make sense to you and will help you to understand the static classes.
It might help to think of "static" and "instance" in terms of memory addressing.
An object that is static exists in one and only one location in memory; you can't create instances of it because by definition it has been stated that it will be found in one particular location. It is "static" and unchanging. The creation of the object is implicit rather than explicit.
var result = Math.Pow(3, 3); // static - Math class can't be instanced
An object that isn't static can be instanced one or more times; you're saying, "Create for me an object of this type" and the object is given a memory address. You can create multiple instances that all exist in different memory addresses. The creation of the object is explicit using the new keyword.
var Ted = new Employee(); // instance - creates a new object at a new address
This is where people get into trouble in ASP .NET web programming; static classes are created once per Application Domain and their constructors are therefore only called once.
A static class is one that cannot be instantiated. Therefore, it cannot be used as a 'template" for multiple instances of some object that conforms to the class definition as a normal class can. In a normal class, the data members defined are created for each "instance" of the class, and each "instance" has it's own set of these data members, so these instances represent individual "entities" or complex in-memory data structures for some object (which you coded the class to represent).
When you define (code) a static class, all of it's data fields must also be static, meaning that they cannot be instantiated once for each instance of the class, (you can't create instances of a static class ). Static classes are useful only when you just need a container to hold methods that do not depend on the state of some object or data structure being managed by the application (like an add function, or a string formatter, etc.)