"} expected" error in c# program - c#

I have made two classes in C# but when I created the constructor for the second class it gave me the error "} expected" I don't understand what is wrong as there are enough sets of {}. It also gives the same error for the very final curly brace at the bottom of the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cars
{
class Program
{
static void Main(string[] args)
{
Car c1 = new Car("Audi","A1","AB12 CDE",1985, 15000);
Console.WriteLine(c1);
string str = Console.ReadLine();
}
}
class Fleet
{
public Fleet()
{
public Car[] carArray = new Car[100];
}
}
class Car
{
public string Make { get; set; }
public string Model { get; set; }
public string Registration { get; set; }
public int Year { get; set; }
public int Value { get; set; }
public Car(string make, string model, string registration, int
year, int value)
{
Make = make;
Model = model;
Registration = registration;
Year = year;
Value = value;
}
public override string ToString()
{
return string.Format("Make: {0}\nModel: {1}\nRegistration: {2}\nYear: {3}\nValue: {4:C}", Make, Model, Registration, Year, Value);
}
}
}

In your class
class Fleet
{
public Fleet()
{
public Car[] carArray = new Car[100];
}
}
you have carArray declared public but it's in the constructor. You can't have modifiers in methods. Any variable declared in a method is always only seen in the scope of that method. I'm assuming you need it in the class and not the constructor so just move it out like so...
class Fleet
{
public Car[] carArray = new Car[100];
public Fleet()
{
}
}
and all is good.

Above, in the "Fleet" class inisde the constructor you have tried to created an array object "carArray" along with initialization.
Because of this you are getting this error.
The constructor are meant for initialize the class variavles/objects, not for declaration of variavles/objects.
Try for this, it will work.
class Fleet
{
public Car[] carArray = null;
public Fleet()
{
carArray = new Car[100];
}
}

Related

c# Generic Query Builder

I would like to know if there is a better way to write this code.The main target is to let 'Select method' know which colum of our object we going to use in our query. I would like to have something like second code:
internal class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
}
public interface IRepository<T> where T : class
{
void Select(string[] table);
}
public class Repository<T> : IRepository<T> where T : class
{
public void Select(string[] table)
{
// Build Query
}
}
public partial class Main
{
public Main()
{
Repository<Employee> empRepository = new Repository<Employee>();
Employee myemp = new Employee();
string[] selectedColums = {nameof(myemp.ID), nameof((myemp.Sex) };
empRepository.Select(selectedColums);
}
}
Now in Main class i will do something like this:
public Main()
{
Repository<Employee> empRepository = new Repository<Employee>();
empRepository.Select(string[] selectedColums = {=>.Sex , =>.Name });
}
We Have already our Object so why we should have a new declaration of type Employee!
Thanks a lot.
Putting #xanatos suggestions into code, is this what you're looking for?
public Main()
{
Repository<Employee> empRepository = new Repository<Employee>();
string[] selectedColums = { nameof(Employee.ID), nameof(Employee.Sex) };
empRepository.Select(selectedColums);
}
Added bonus, nameof gets evaluated at compile time. So it can help catch errors before execution:
nameof(Employee.PropertyThatDoesntExist)
The above won't even compile.

Get properties from derived class in base class

How do I get properties from derived class in base class?
Base class:
public abstract class BaseModel {
protected static readonly Dictionary<string, Func<BaseModel, object>>
_propertyGetters = typeof(BaseModel).GetProperties().Where(p => _getValidations(p).Length != 0).ToDictionary(p => p.Name, p => _getValueGetter(p));
}
Derived classes:
public class ServerItem : BaseModel, IDataErrorInfo {
[Required(ErrorMessage = "Field name is required.")]
public string Name { get; set; }
}
public class OtherServerItem : BaseModel, IDataErrorInfo {
[Required(ErrorMessage = "Field name is required.")]
public string OtherName { get; set; }
[Required(ErrorMessage = "Field SomethingThatIsOnlyHereis required.")]
public string SomethingThatIsOnlyHere{ get; set; }
}
In this example - can I get the "Name" property from ServerItem class while in BaseModel class?
EDIT:
I'm trying to implement model validation, as described here:
http://weblogs.asp.net/marianor/archive/2009/04/17/wpf-validation-with-attributes-and-idataerrorinfo-interface-in-mvvm.aspx
I figured that if I create some base model with (almost) all of the validation magic in it, and then extend that model, it will be okay...
If both classes are in the same assembly, you can try this:
Assembly
.GetAssembly(typeof(BaseClass))
.GetTypes()
.Where(t => t.IsSubclassOf(typeof(BaseClass))
.SelectMany(t => t.GetProperties());
This will give you all the properties of all the subclasses of BaseClass.
If you require that a derived class must implement a method or property, you should introduce that method or property into the base class as an abstract declaration.
For example, for your Name property, you would add to the base class:
public abstract string Name { get; set; }
Then any derived classes must implement it, or be abstract classes themselves.
Once you have added the abstract version of the Name property to the base class, you will be able to access it in the base class anywhere except in the base class's constructor.
If you must do literally fetch property of derived class from within base class, you can use Reflection, for example - like this...
using System;
public class BaseModel
{
public string getName()
{
return (string) this.GetType().GetProperty("Name").GetValue(this, null);
}
}
public class SubModel : BaseModel
{
public string Name { get; set; }
}
namespace Test
{
class Program
{
static void Main(string[] args)
{
SubModel b = new SubModel();
b.Name = "hello";
System.Console.Out.WriteLine(b.getName()); //prints hello
}
}
}
This is not recommended, though, and you most probably should rethink your design like Matthew said.
As for not throwing properties to your base classes -- you can try to decouple base and deriving classes into unrelated objects and pass them via constructors.
Another way to solve this issue by create virtual property in base class and override it to derived class.
public class Employee
{
public virtual string Name {get; set;}
}
public class GeneralStaff
{
public override string Name {get; set;}
}
class Program
{
static void Main(string[] args)
{
Employee emp = new GeneralStaff();
emp.Name = "Abc Xyz";
//---- More code follows----
}
}
Okay, I solved this problem slightly different than the author of this post: http://weblogs.asp.net/marianor/archive/2009/04/17/wpf-validation-with-attributes-and-idataerrorinfo-interface-in-mvvm.aspx
public abstract class BaseModel : IDataErrorInfo {
protected Type _type;
protected readonly Dictionary<string, ValidationAttribute[]> _validators;
protected readonly Dictionary<string, PropertyInfo> _properties;
public BaseModel() {
_type = this.GetType();
_properties = _type.GetProperties().ToDictionary(p => p.Name, p => p);
_validators = _properties.Where(p => _getValidations(p.Value).Length != 0).ToDictionary(p => p.Value.Name, p => _getValidations(p.Value));
}
protected ValidationAttribute[] _getValidations(PropertyInfo property) {
return (ValidationAttribute[])property.GetCustomAttributes(typeof(ValidationAttribute), true);
}
public string this[string columnName] {
get {
if (_properties.ContainsKey(columnName)) {
var value = _properties[columnName].GetValue(this, null);
var errors = _validators[columnName].Where(v => !v.IsValid(value)).Select(v => v.ErrorMessage).ToArray();
return string.Join(Environment.NewLine, errors);
}
return string.Empty;
}
}
public string Error {
get { throw new NotImplementedException(); }
}
}
Maybe it will help somebody.
Scan your assembly for all inherited classes from BaseModel and create dictionary like this:
Dictionary<Type, Dictionary<string, Func<BaseModel, object>>>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TESTNEW
{
public abstract class BusinessStructure
{
public BusinessStructure()
{ }
public string Name { get; set; }
public string[] PropertyNames{
get
{
System.Reflection.PropertyInfo[] Pr;
System.Type _type = this.GetType();
Pr = _type.GetProperties();
string[] ReturnValue = new string[Pr.Length];
for (int a = 0; a <= Pr.Length - 1; a++)
{
ReturnValue[a] = Pr[a].Name;
}
return ReturnValue;
}
}
}
public class MyCLS : BusinessStructure
{
public MyCLS() { }
public int ID { get; set; }
public string Value { get; set; }
}
public class Test
{
void Test()
{
MyCLS Cls = new MyCLS();
string[] s = Cls.PropertyNames;
for (int a = 0; a <= s.Length - 1; a++)
{
System.Windows.Forms.MessageBox.Show(s[a].ToString());
}
}
}
}

Instantiating a class given a generic abstract type

Using this model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
#region Abstracts definitions
abstract class AnAbstract
{
public string Name { get { return this.GetType().Name; } }
public bool IsNumeric { get { return this is ANumericAbstract; } }
public /*abstract*/ string Description = default(string);
}
abstract class ANumericAbstract : AnAbstract
{
public /*abstract*/ double Min = double.MinValue;
public /*abstract*/ double Max = double.MaxValue;
}
abstract class ANonNumericAbstract : AnAbstract
{
public List<Object> objects = new List<Object>();
}
#endregion Abstracts definitions
#region Concrete definitions
class NumericImpl : ANumericAbstract
{
new public const string Description = "A numeric implementation";
new public const double Min = 0;
new public const double Max = 1000;
public NumericImpl()
{
}
}
abstract class AnotherImpl : ANonNumericAbstract
{
public AnotherImpl()
{
objects.Add("one");
objects.Add("two");
objects.Add("three");
}
}
class SideA : AnotherImpl
{
new public const string Description = "Disc side A";
}
class SideB : AnotherImpl
{
new public const string Description = "Disc side B";
}
#endregion Concrete definitions
partial class Parameter
{
public string Name { get; set; }
public string Description { get; set; }
public bool IsNumeric { get; private set; }
public double Min { get; private set; }
public double Max { get; private set; }
public List<Object> Values { get; private set; }
private Parameter()
{
Values = new List<Object>();
}
}
}
With this, I pretend to define a hierarchy of classes for which I can have some abstract properties (Name,Description,IsNumeric) and at the end of the hierarchy there should be some classes which mandatorily define those properties; in the case of ANumericAbstract they should have additional specific properties, e.g. Min and Max.
Now here's the problem.
I'm attemtping to be able to create instances of Parameter which take a generic AnAbstract and read from it some values to fill in the Parameter properties, à la
Parameter<ANumericAbstract> ParamNum = new Parameter<NumericImpl>();
where a Parameter constructor would take in the passed type and "fill in the blanks". In other words, I'm trying something like:
using System;
namespace ConsoleApplication1 {
partial class Parameter
{
public static Parameter NewParameter<T>() where T : AnAbstract
{
Parameter Parameter = new Parameter();
// THESE DON'T WORK:
this.Name = T.Name;
this.Description = T.Description;
this.IsNumeric = T.IsNumeric;
if (this.IsNumeric)
{
this.Min = (T as ANumericAbstract).Min;
this.Max = (T as ANumericAbstract).Max;
}
else
{
foreach(Object val in (T as ANonNumericAbstract).Values)
{
this.Values.Add(val);
}
}
return Parameter;
}
}
class Program
{
private AnAbstract Number = new NumericImpl();
static void Main(string[] args)
{
}
// THESE DON'T WORK:
private static Parameter<ANumericAbstract> ParameterNum =
Parameter.NewParameter<NumericImpl>();
private static Parameter<ANonNumericAbstract> ParameterA =
Parameter.NewParameter<SideA>();
private static Parameter<ANonNumericAbstract> ParameterB =
Parameter.NewParameter<SideB>();
}
}
Obviously the syntax is invalid, but I'm not sure if I'm going in the right direction. Is there some Generics syntax that I'm not using properly? Should I just be done with it and use Getters and Setters à la Java? :-) At this point, just doing the
Parameter par = new Parameter { Name = NumericImpl.Name, /* ... */ };
might seem more sensible...
Firstly you should not use New keyword on your properties.
Consider virtual keyword:
abstract class AnAbstract
{
public virtual string Name { get { return this.GetType().Name; } }
public virtual string Description { get { return String.Empty; } }
}
abstract class ANumericAbstract : AnAbstract
{
public virtual double Min = double.MinValue;
}
class NumericImpl : ANumericAbstract
{
public override string Description { get { return "A numeric implementation"; } }
public override double Min { get { return 0; } }
}
1) You can place an instance of you type in Parameter constructor and have Parameter instance.
partial class Parameter
{
public Parameter(AnAbstract inputObject)
{
this.Name = inputObject.Name;
// etc
}
}
private static Parameter ParameterNum = new Parameter(new NumericImpl());
2) The second way is to use reflection to create an instance of object with initial parameters.
partial class Parameter<T> where T : AnAbstract
{
public static Parameter<T> NewParameter<T>() where T : AnAbstract
{
Parameter<T> parameter = new Parameter<T>();
AnAbstract instance = (AnAbstract)Activator.CreateInstance(typeof(T));
parameter.Name = instance.Name;
// etc
return parameter;
}
}
private static Parameter<NumericImpl> ParameterNum =
Parameter<NumericImpl>.NewParameter();
3) Make Parameter class static and create in via static constructor.
static partial class Parameter<T> where T : AnAbstract
{
public static string Name { get; set; }
//etc
}
static partial class Parameter<T> where T : AnAbstract
{
static Parameter ()
{
AnAbstract instance = (AnAbstract)Activator.CreateInstance(typeof(T));
Parameter<T>.Name = instance.Name;
//etc
}
}
In the last example you can use this class like this:
String someName = Parameter<NumericImpl>.Name;

List a classes generic interface names

I have this c# code;
case "Cafe":
source.trendItem = new TrendingLocation<ITrendingCafe>();
break;
case "Pub":
source.trendItem = new TrendingLocation<ITrendingPub>();
break;
etc
a trendItem is defined like this;
public class TrendingItem<T> where T : ITrendingItem
{
public T trendItem { get; set; }
}
Then I have this;
public List<TrendingItem<ITrendingItem>> trendItems { get; set; }
Now for each item in the above trendItems i want to get the interfaces.
I tried using;
string g = fvm.trendItems[4].trendItem.GetType().GetInterfaces()[1].Name;
and
string g = typeof(TrendingLocation<>).GetInterfaces()[0].Name;
but neither of these lists the Generic interface such as ITrendingCafe, ITrendingRestaurant etc.
Is there a way I can get the name of the generic interface name?
You want to use the Type's GetGenericArguments method.
If I understand your structure, it will be something like:
Type[] typeArguments = fvm.trendItems[4].trendItem.GetType().GetGenericArguments();
foreach (Type tParam in typeArguments)
{
// Compare the type with the interface you are looking for.
}
I take it that ITrendingCafe is an interface that implements ITrendingItem. I wrote a quick program that takes and displays all of the interfaces that T Implements:
using System;
using System.Collections.Generic;
namespace TestConsoleApplication
{
public interface ITrendingItem
{
string ItemName { get; set; }
}
public interface ITrendingCafe : ITrendingItem
{
string CafeName { get; set; }
}
public class TrendingItem<T> where T : ITrendingItem
{
public T trendItem { get; set; }
}
public class Cafe : ITrendingCafe
{
public string ItemName { get; set; }
public string CafeName { get; set; }
}
class Program
{
static void Main(string[] args)
{
var test = new List<TrendingItem<ITrendingItem>> { new TrendingItem<ITrendingItem> { trendItem = new Cafe() } };
foreach (var trendingItem in test[0].trendItem.GetType().GetInterfaces())
{
Console.Out.WriteLine(trendingItem.Name);
}
Console.ReadKey();
}
}
}
And here is the output:
As you can see, the interface is there. Just loop through and find the one you need!

crash Console Application

This is my problem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public abstract class EntityMember<T>
{
public T Value { get; set; }
}
public class Int32EntityMember : EntityMember<int?>
{
}
public class StringEntityMember : EntityMember<string>
{
}
public class GuidEntityMember : EntityMember<Guid?>
{
}
public class Entity
{
public GuidEntityMember ApplicationId { get; private set; }
public Int32EntityMember ConnectedCount { get; private set; }
public GuidEntityMember MainApplicationId { get; private set; }
public Int32EntityMember ProcessId { get; private set; }
public StringEntityMember ProcessName { get; private set; }
}
class Program
{
static void Main(string[] args)
{
Entity entity2 = new Entity();
Guid empty = Guid.NewGuid();
Guid applicationId = Guid.NewGuid();
int Id = 10;
string name = "koko";
entity2.MainApplicationId.Value = new Guid?(empty);
entity2.ApplicationId.Value = new Guid?(applicationId);
entity2.ProcessId.Value = new int?(Id);
entity2.ProcessName.Value = name;
entity2.ConnectedCount.Value = 1;
}
}
}
The application has totally blocked on the line:
entity2.MainApplicationId. Value = new Guid? (empty);
Why?
The exception you're receiving is:
Object reference not set to an instance of an object.
This is because entity2.MainApplicationId is null. Your Entity class does not have a constructor to set MainApplicationId to be not null, hence the error you're seeing.
Adding a constructor to your Entity class as shown in the code below results in your code running without error:
public Entity()
{
ApplicationId = new GuidEntityMember();
ConnectedCount = new Int32EntityMember();
MainApplicationId = new GuidEntityMember();
ProcessId = new Int32EntityMember();
ProcessName = new StringEntityMember();
}
Using Auto-Implemented properties does not result in the underlying fields (that are created and managed on your behalf by the compiler) being new'd when the instance is constructed. Thus the two properties that follow are not the same:
public MyClass MyProperty { get; private set; }
private MyClass _myOtherProperty = new MyClass();
public MyClass MyOtherProperty
{
get
{
return _myOtherProperty;
}
set
{
_myOtherProperty = value;
}
}
Try changing the line to a type cast:
entity2.ApplicationId.Value = (Guid?)(applicationId);

Categories