I'm having trouble understanding why a part of my code can't resolve another part.
I have this class that contains two properties. The second property relies on the first, but it keeps throwing this error:
cannot resolve symbol 'yearlyEmployees'
public class Financials
{
public static IEnumerable<SalaryEntity> yearlyEmployees = FactoryManagement(12345);
//cannot resolve symbol 'yearlyEmployees'
public static IEnumerable<CompanyEntity> YearlyGroup(IList<yearlyEmployees> allExempt)
{
}
}
I'm sure there's an easy answer, but I just can't find it.
Thanks!
yearlyEmployees is a variable name, not a class name. Try:
public static IEnumerable<CompanyEntity> YearlyGroup(IList<SalaryEntity> allExempt)
You must use the type SalaryEntity as item for your list.
public static IEnumerable<CompanyEntity> YearlyGroup(IList<SalaryEntity> allExempt) {}
That is because you don't have a type of yearlyEmplyee - that is your variable.
Instead:
public static IEnumerable<CompanyEntity> YearlyGroup(IList<SalaryEntity> allExempt)
{ }
And then just pass a collection of SalaryEntity to the function. If you always want to process only yearlyEmployees (which I don't think is the case but not sure) then just call it from within the method `Financials.yearlyEmployees'.
Related
Hi so I'm trying to convert a string named compToAdd into a type and im not sure how to do it, I tried googling for almost 5 hours now and here I am.
The goal would be to make slot.AddComponent<compToAddType>(); run properly
Here is a snippet of the code:
public string foundationComp;
public string turretComp;
public void buildFoundation()
{
Build(foundationComp);
}
public void buildTurret()
{
Build(turretComp);
}
public void Build(string compToAdd)
{
Type compToAddType = Type.GetType(compToAdd); //I thought this line would convert the string into a type
slot.AddComponent<compToAddType>(); // but then I get an error here saying that compToAddType is a variable thats being used like a type..so how am I supposed to convert it?
//just note that 'slot' here have no problem and is a gameobject the problem is on the word 'compToAddType'
}
Thank you in advance.
In general see Type.AssemblyQualifiedName.
If you don't have that you will need to at least have a reference to the Assembly in question and then use Assembly.GetType.
You can also get the assembly if you know at least one type from the according assembly via Assembly.GetAssembly(theKnownType)
That said, you can not use the generic version GameObject.AddComponent<T>() since the type-parameter of generics need to be compile-time constant!
You can however simply use the non-generic version of GameObject.AddComponent(Type)
public void Build(string compToAdd)
{
Type compToAddType = Type.GetType(compToAdd);
slot.AddComponent(compToAddType);
}
(Actually there even was an overload directly taking a string as parameter but it was deprecated.)
Finally I personally would avoid it completely if possible! Instead of relying on your strings being correct, why not rather use e.g.
public void buildFoundation()
{
slot.AddComponent<FoundationComponnet>();
}
public void buildTurret()
{
slot.AddComponent<TurretComponent>();
}
I have this code:
public class NewFrame
{
public NewFrame(string iconSource = Const.Car,
string iconColor = Const.Red)
{
When I try and use it then it's telling me I am missing a default constructor. How can I add one of these and still make the code use the default values for iconBackgroundColor and IconSource? I thought that adding in those defaults with the = Const. would make it work but it seems like it doesn't think my constructor is a default (with no params).
You just have to add another empty overload and call the required constructor with defaults. See below:
public class NewFrame
{
public NewFrame() : this(Const.Car, Const.Red){
}
public NewFrame(string iconSource,
string iconColor)
{
...
}
}
By having two optional parameters, you don't actually create 4 different constructor declarations under the hood (one with both parameters, one with the first parameter, one with the second parameter, and one with neither). There is still only one constructor, with two parameters. It's just that C# recognises that the parameters are optional, and has syntactic sugar to let you omit them when you call the constructor.
However, if you use reflection to create an instance of your class (probably whatever the thing that requires a default constructor is doing), and you attempt to invoke the parameterless constructor, it won't find one, because there is no syntactic sugar in reflection.
Here is an example:
class MainClass
{
public static void Main(string[] args)
{
Type t = typeof(MainClass);
object o = Activator.CreateInstance(t, 1);
Console.WriteLine(o);
}
public MainClass(int a = 10)
{
}
}
If you use typeof(MainClass).GetConstructors(), it will tell you that there is only one.
To actually declare a default constructor, you can do:
public class NewFrame
{
public NewFrame(string iconSource = Const.Car,
string iconColor = Const.Red)
{
...
}
public NewFrame() : this(Const.Car, Const.Red) { }
}
For what it's worth, when I do something like this, I take the route that #VyacheslavBenedichuk's answer is showing.
I'm not sure what your complaint is. This code compiles for me:
public class TestConstructor
{
public TestConstructor(string what = Const.Car, string color = Const.Red)
{
}
public static void Test()
{
var tc = new TestConstructor();
}
public class Const
{
public const string Car = "car";
public const string Red = "red";
}
}
What do your definitions of Const.Car and Const.Red look like? Where are you seeing the error?
But, if you use something that requires a default constructor, then this will not work. For example, this will fail at runtime:
var tc2 = Activator.CreateInstance(typeof(TestConstructor));
Please, when you are reporting an error, describe it exactly - in particular say whether it's a runtime or a compile-time error, the exact wording of the error, and the context in which the error occurs. In this case (the call to CreateInstance) will result in a System.MissingMethodException: 'No parameterless constructor defined for this object.'
In this case, you need to follow #VyacheslavBenedichuk's advice
I'm fairly new to C# but have extensive experience in Objective-C and OOP. I'm using Json.NET to automatically parse API responses to objects. It so happens that one of the objects returned has a property named protected. Obviously this is a problem, because protected is a keyword for class member declaration.
"protected": true
Is it possible to add a member with the name protected at all?
Is it possible to add setters and getters that get triggered, if the parser tries to set the protected property? (but assign the value to a private member named _protected)
Should I modify the parser to behave different when he encounters a property named protected?
Thanks for any advice.
1:
For question #1: You can put an # symbol before it any keyword you want to use as a variable name.
E.g.
public string #protected {get; set; }
I recommend against doing this, however. You should be able to remap the "protected" field in your JSON to a different property in your POCO.
2:
private string _protected;
public string #protected
{
get
{
//any additional code you want
return _protected;
}
set
{
//any additional code you want
_protected = value;
}
}
3:
Up to you!
I implemented this solution:
[JsonProperty("protected")] public bool Protected { get; set; }
Like Daniel Mann suggested in his comment:
In C#, I am defining a static field of a specific class. From within the class, I want to be able to display the name of the static field, pretty much like this:
public class Unit {
public string NameOfField { get { return ...; } }
}
public static Unit Hectare = new Unit();
If I now access:
Hectare.NameOfField
I want it to return:
Hectare
I know there is a static function System.Reflection.MethodBase.GetCurrentMethod(), but as far as I can tell there is no way to get the name of the instance containing this current method?
There is also the System.RuntimeFieldHandle structure, but I have not been able to identify any GetCurrentFieldHandle() method.
I am not sure if I am missing something obvious?
Any help on this is very much appreciated.
You should not count on variable names in you developments as they do not exits at runtime.
It's better to initialize Unit with a name directly:
public class Unit {
public Unit(string name)
{
NameOfField = name;
}
public string NameOfField { get; private set;} }
}
public static Unit Hectare = new Unit("Hectare");
Only way around this will be to store that information in the class:
public static Unit Hectare = new Unit("Hectare");
When your code is compiled all variable names are lost and replaced by internal references. There is no way to get that name again.
You can use Reflection to obtain class Fields and properties. Like below:
Suppose you have class with one property:
class Test
{
public static string MySupperField
{
get
{
return "Some symbols here";
}
}
}
......
You can read the property name in such way:
public string[] GetClassStaticNames(Type T)
{
string[] names;
System.Reflection.PropertyInfo[] props = T.GetProperties(); // This will return only properties not fields! For fields obtaining use T.GetFields();
names = new string[props.Count()];
for (int i = 0; i < props.Count(); i++)
{
names[i] = props[i].Name;
}
return names;
}
Hope this will help.
[EDIT]
Returning to your question - No you cant obtain name of current variable.
What you are asking about cant be done because of classes nature, they are objects in memory and reference to one object can be held in many variables, and when you are requesting value of instance field or property it will be actually performed operation with object in memory not with variable wich holds reference to that object. So obtaining name of variable wich holds reference to current instance have no sence
Thanks everyone who has taken the time to answer and discuss my question.
Just to let you know, I have implemented a solution that is sufficient for my needs. The solution is not general, and it has some pitfalls, but I'd thought I share it anyway in case it can be of help to someone else.
This is in principle what the class that is used when defining fields looks like:
public class Unit : IUnit {
public NameOfField { get; set; }
...
}
As you can see, the class implements the IUnit interface, and I have provided a public setter in the NameOfField property.
The static fields are typically defined like this within some containing class:
public static Unit Hectare = new Unit();
My solution is to set the NameOfField property through reflection before the field is used in the implementation.
I do this through a static constructor (that of course needs to be invoked before the Unit fields are accessed.
I use Linq to traverse the executing assembly for the relevant fields, and when I have detected these fields (fields which type implements the IUnit interface), I set the NameOfField property for each of them using the Any extension method:
Assembly.GetExecutingAssembly().GetTypes().
SelectMany(type => type.GetFields(BindingFlags.Public | BindingFlags.Static)).
Where(fieldInfo => fieldInfo.FieldType.GetInterfaces().Contains(typeof(IUnit))).
Any(fieldInfo =>
{
((IUnit)fieldInfo.GetValue(null)).NameOfField= fieldInfo.Name;
return false;
});
There are some shortcomings with this approach:
The static constructor has to be invoked through manual intervention before any Unit fields can be accessed
The NameOfField setter is public. In my case this is no problem, but it might be when applied in other scenarios. (I assume that the setter could be made private and invoked through further reflection, but I have not taken the time to explore that path further.)
... ?
Either way, maybe this solution can be of help to someone else than me.
I'm working on a project for school (going for my BA in CIS) and I've come across this issue with a class function.
public static int GetNumberCreated()
{
// return the total number of airplanes created using the class as the blueprint
return numberCreated; // returns the number of airplanes created
}//end of public int GetNumberCreated()
It's for a program to return the value of how many airplanes you've made thus far in this small C# program.
I declared numberCreated at the beginning:
private int numberCreated;
I get the classic error "An object reference is required for the non-static field, method, or property" I've done a decent amount of research trying to figure out what is going on but i've come up with nothing.
I did however set a property at the bottom of the class so that a form would be able to access the variable:
public int NumberCreated { get; set; }
I also attempted changing the property to this:
public int NumberCreated { get { return numberCreated; } set { numberCreated = value; } }
with no luck. >.>'
What am i doing wrong?
You need to declare your number created int as static.
eg public static int NumberCreated {get;set;}
You can access a static member from a non static method, but you cant access a non static member from a static method. eg, instance variables are not accessable from static methods.
It's a simple thing - you need to add the "static" keyword before your method signature, like so:
public static int NumberCreated { get; set; }
Then you can increment / decrement like so:
AirplaneFactory.NumberCreated++ / AirplaneFactory.NumberCreated--
GetNumberCreated is a static method. The numberCreated is a variable that is created with the object of this class. So, the static method doesn't know where to look, because there is no such variable.
You need a private static int.
In a nutshell, your static method can be called even when "numberCreated" has not been brought into existence yet. The compiler is telling you that you're trying to return a baby without any prior guarantee that it's been born.
Change numberCreated to a static property and it'll compile.