Can I access the internal variables outside the class?
If I have an internal variable like this:
Class Example
{
internal string CommonHome = "C:/myfile/";
}
How to access this CommonHome from outside the class or another class?
There is any possible way for accessing this?
internal variable are accessible in current dll only.
You can have look at msdn for this => link
Here is some code snippets from there.
public class BaseClass
{
internal static int intM = 0;
}
public class TestAccess
{
static void Main()
{
BaseClass myBase = new BaseClass(); // Ok.
BaseClass.intM = 444; // CS0117
}
}
You can access the internal members within the assembly you declared them in other classes. Since your inter data member is instance member you need to create instance of Example in a class you want CommonHome
Example ex = new Example();
string s = ex.CommonHome;
You probably need to give type of CommonHome which is string I guess
Class Example
{
internal string CommonHome = "C:/myfile/";
}
You better use property for CommonHome instead of public data member as you may need to apply some business rule later to this. This is a very good post about the properties, Why Properties Matter.
Class Example
{
internal string CommonHome { get; set; }
internal Example()
{
CommonHome = "C:/myfile/";
}
}
The internal keyword is an access modifier for types and type members.
Internal types or members are accessible only within files in the same
assembly, MSDN.
You can read more about access modifiers here.
Related
What's the difference between static classes, and static methods? I want to learn the differences, and when I might use one vs. the other.
For example, I have a class like this:
static class ABC
{
public int a;
public void function_a()
{
a = 10;
}
}
and another class like this:
class DEF
{
public static int a;
public static void function_a()
{
a= 10;
}
}
I have used the second type of class many times, and I know the usage. What's the usage of the first example?
Your first example will not compile, a static class must have all static members.
The difference between just using some static methods and a static class is that you are telling the compiler that the class cannot be instantiated. The second example you can create an object of the DEF class even though there are no instance methods in it. The ABC class cannot be instantiated with the new operator (will get a compile-time error).
When to Use Static Classes
Suppose you have a class CompanyInfo that contains the following methods to get information about the company name and address.
C#
class CompanyInfo
{
public string GetCompanyName() { return "CompanyName"; }
public string GetCompanyAddress() { return "CompanyAddress"; }
//...
}
These methods do not need to be attached to a specific instance of the class. Therefore, instead of creating unnecessary instances of this class, you can declare it as a static class, like this:
C#
static class CompanyInfo
{
public static string GetCompanyName() { return "CompanyName"; }
public static string GetCompanyAddress() { return "CompanyAddress"; }
//...
}
Use a static class as a unit of organization for methods not associated with particular objects. Also, a static class can make your implementation simpler and faster because you do not have to create an object in order to call its methods. It is useful to organize the methods inside the class in a meaningful way, such as the methods of the Math class in the System namespace.
Inside of a public class:
public static class LogReporting
I have the following method:
public void RunTimerJobs()
{
SPAdministrationWebApplication centralAdmin = SPAdministrationWebApplication.Local;
try
{
foreach (SPService service in centralAdmin.Farm.Services)
{
Guid traceGuid = new Guid("d3beda82-38f4-4bc7-874f-ad45cebc9b35");
Guid eventGuid = new Guid("3ea057b3-0391-4c33-ac8d-412aecdda97d");
var traceJob =
from jobDefinition in service.JobDefinitions
where jobDefinition.Id == traceGuid
select jobDefinition;
if (traceJob != null && traceJob.Count() == 1)
{
traceJob.First().RunNow();
}
var eventJob =
from jobDefinition in service.JobDefinitions
where jobDefinition.Id == eventGuid
select jobDefinition;
if (eventJob != null && eventJob.Count() == 1)
{
eventJob.First().RunNow();
}
}
}
catch (Exception ex)
{
//Loggers.SharePointLogger logger = new Loggers.SharePointLogger();
//logger.WriteTrace(ex.Message, LogProduct.MonitoringView, LogTraceSeverity.Unexpected);
}
However it will not allow me to compile citing that RunTimerJobs() "cannot declare instance members in a static class"
To my knowledge, none of the 'instance members' I declare are able to be labeled as static, so is there just a fundamental issue with the setup (i.e. a static class) or am I missing some little snippet?
Your class is static thus you cannot have any instance members because you will never instantiate the class.
To be able to use the RunTimerJobs() method you would need to create an instance of the LogReporting class, i.e.
LogReporting logReporting = new LogReporting();
logReporting.RunTimerJobs();
This obviously won't work though because your class is defined as static and you cannot create instances of it.
Either make your method static or remove the static keyword from your class declaration - depending on what you require.
I see no instance related logic in your method so it should be safe to mark it as static.
Remember
Classes can have a mixture of instance and static members as long as the class isn't marked static.
And
Only mark classes as static when you know that ALL members (properties, methods etc...) will be static as well.
The compiler's being pretty clear here. You're declaring a static class, and static classes can only contain static members. So this is okay:
public class NonStaticClass
{
public void InstanceMethod() {}
}
And this is okay:
public static class StaticClass
{
public static void StaticMethod() {}
}
But this isn't:
public static class StaticClass
{
public void InstanceMethod() {}
}
If you wanted to declare instance members, why did you declare LogReporting as a static class?
When class marked as static, then all it's members should be static (instances creation is not allowed). You can read more about static classes on msdn.
So, if you want to have instance (non-static) method, then remove static keyword from class definition:
public class LogReporting
{
public void RunTimerJobs()
{
//...
}
}
In this case you should create LogReporting instance to call your method:
LogReporting log = new LogReporting();
log.RunTimerJobs();
Another option for you - making your method static:
public static class LogReporting
{
public static void RunTimerJobs()
{
//...
}
}
In this case you don't need instance of LogReporting:
LogReporting.RunTimerJobs();
Did you try:
public static void RunTimerJobs()
For a static class, the members must also be static. If you are unable make the members static, then you must make the class non-static as well.
It's generally a good idea to use non-static classes if you can, as static classes increase the complexity of unit testing as they cannot be mocked out easily. Of course if you have a legitimate need to use a static class, then by all means do so.
I'm setting up some demo code for a beginner session on accessibility and I found that I am able to access an internal protected property from a derived class. What am I missing?
Assembly 1
namespace Accessibility
{
class Program
{
static void Main(string[] args)
{
ExampleClass c = new ExampleClass();
c.Go();
//c.Prop1 = 10;
}
}
class ExampleClass : DerivedClass
{
public void Go()
{
this.Prop1 = 10;
this.Prop2 = 10;
//this.Prop3 = 10; //Doesn't work
//this.Prop4 = 10; //Doesn't work
this.Prop5 = 10; //why does this work?!
this.DoSomething();
}
}
}
Assembly 2
namespace Accessibility.Models
{
public class BaseClass
{
public int Prop1 { get; set; }
protected int Prop2 { get; set; }
private int Prop3 { get; set; }
internal int Prop4 { get; set; }
internal protected int Prop5 { get; set; }
//internal public int Prop6 { get; set; } //Invalid
//internal private int Prop7 { get; set; } //Invalid
public BaseClass()
{
this.Prop3 = 27;
}
}
public class DerivedClass : BaseClass
{
public void DoSomething()
{
this.Prop1 = 10;
this.Prop2 = 10;
//this.Prop3 = 10; //Doesn't work
this.Prop4 = 10;
this.Prop5 = 10;
PropertyInfo Prop3pi = typeof(DerivedClass).GetProperty("Prop3", BindingFlags.Instance | BindingFlags.NonPublic);
int value = (int)Prop3pi.GetValue(this, null);
}
}
}
Notice in ExampleClass.Go I can set a value to Prop5. Why? It's marked as internal protected but I can't set a value on Prop4 (marked as internal)
internal protected means "internal to the assembly OR an inherited class". So yes, if you have a public class with an protected internal member, another class that inherits that type in a different assembly can still access it because of the protected modifier:
protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.
Reference: http://msdn.microsoft.com/en-us/library/ms173121.aspx
This is a limitation of the C# language. The CLR supports the "Internal AND Protected" notion. There is evidence of this with the MethodAttributes.FamANDAssem enumeration if you were emitting your own IL. If you really wanted this feature, you could do some IL post processing with something like Mono.Cecil. Why the C# language does not expose this is only a guess: little need for it.
Because it's how internal protected is intended to work. Access is given for either children in inheritance tree (protected part) or for the same assembly (internal part) - see Access Modifiers on MSDN.
And your ExampleClass is in the inheritance tree of BaseClass, which defines Prop5. So the access is thanks to protected part.
The protected keyword is a member access modifier. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.
http://msdn.microsoft.com/en-us/library/bcd5672a(v=vs.71).aspx
By combining the protected and internal keywords, a class member can be marked protected internal — only derived types or types within the same assembly can access that member.
http://msdn.microsoft.com/en-us/library/ms173121(v=vs.80).aspx
It looks like protected internal means protected or internal.
Basically, it doesn't seem to work like that.
See - http://msdn.microsoft.com/en-us/library/ba0a1yw2(VS.80).aspx
protected internal acts as an OR - access is restricted to derived classes or to the current assembly.
By combining the protected and internal keywords, a class member can be marked protected internal — only derived types or types within the same assembly can access that member.
This MSDN article answers all your questions.
Protected means that it is shared only with descendant classes, only private means that it can't be accessed by anyone else.
Edit: Hans comment makes your question a little more clear. When you combine modifiers like that, they combine inclusively not exclusively. It is accesse in all the ways internal or protected can be.
Late answer but I got caught with the same issue. Eventualy I came up with a partial solution.
internal Int MyInt
{
get;
protected set;
}
It is still visible within the assembly but at least only inherithing classes can actualy change it. It is enough for what I wanted.
I have static variables and methods in a class. Will they be inherited in derived classes or not?
For example:
class A
{
public static int x;
public static void m1()
{
some code
}
}
class B:A
{
B b=new B();
b.m1(); // will it be correct or not, or will I have to write
// new public voim1(); or public void m1();
b.x=20; // will it be correct or not?
}
The static members will be available in the derived class, but you can't access them using an instance reference. Either you access them directly:
m1();
x = 20;
or by using the name of the class:
A.m1();
A.x = 20;
The static members will be available, but you won't be able to reference them on the instance. Instead, reference using the type.
E.g.
class B:A
{
public void Foo()
{
A.m1();
A.x=20;
}
}
Static members are available, but you won't be able to reference them on the instance. Hence you must use the class prefix of the superclass. A.m1().
This is in direct contrast to the Java language where you can access static methods and fields using instance references.
A static member is not associated with an instance because its a Class variable or a Class method, you can access it using the class name. It is usually used to retain general Class information for example number of instances created and etc.
In the following scenario:
public class outerclass
{
public innerClass Ic
{get;set}
public class innerClass
{
}
}
Do you need to instantiate the inner class property before assigning values to it, like this?
public class outerclass
{
public outerclass()
{
this.Ic = new innerClass();
}
public innerClass Ic
{get;set}
public class innerClass
{
}
}
It doesn't matter in what scope class has been declared - you should always work with classes in the same manner: before interacting with a particular class instance you have to create it using new operator.
Yes, unlike a base class you need to instantiate an inner class if you wish to use it.
You can prove this to yourself quite easily by trying it:
public class OuterClass
{
public InnerClass Ic { get; set; }
public class InnerClass
{
public InnerClass()
{
Foo = 42;
}
public int Foo { get; set; }
}
}
public class Program
{
static void Main()
{
Console.WriteLine(new OuterClass().Ic.Foo);
}
}
The above code throws a NullReferenceException because Ic has not been assigned.
I would also advise you to follow the Microsoft naming convention and use pascal case for type names.
In this case the answer doesn't depend on the fact that the class is defined inside your outer class. Because you used the automatic getter/setter, a hidden backing field is used for the property Ic. Like all fields of reference type, this field has a default value of null. Thus if you try to access the members of Ic without setting it to refer to some instance, you can expect a NullReferenceException.
Everything I just said would still be true even if innerClass was defined somewhere else.
No, the property is an instance of the class. The set would set a new instance anyway. No need to construct one unless you want to make sure the get never returns null.