What is the required parameter for casting C# - c#

Minimal reproducible example
Base abstract class:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
namespace YangHandlerTool
{
public abstract class YangNode
{
public string Name { get; set; }
/// <summary>
/// This is here to force YangNode constructor with Name parameter.
/// </summary>
private YangNode() { }
public YangNode(string name) { Name = name; }
}
}
Child that adds "Type" property
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
namespace YangHandlerTool
{
public class Leaf : YangNode
{
public string Type { get; set; }
public Leaf(string leafname) : base(leafname){ }
}
}
Other Child that adds "Type" property
using System;
namespace YangHandlerTool
{
public class LeafList : YangNode
{
public string Type { get; set; }
public LeafList(string leafname) : base(leafname) { }
}
}
Main
using System;
using System.Collections.Generic;
namespace YangHandlerTool
{
class Program
{
static void Main(string[] args)
{
List<YangNode> yangnodes = new List<YangNode>();
yangnodes.Add(new Leaf("leafname"));
for (int i = 0; i < yangnodes.Count; i++)
{
if (IsLeaf(i))
{
///I want to call SetTypeOfNode with the intention to cast to Leaf
SetTypeOfNode(yangnodes[i]);
}
if (IsLeafList(i))
{
///I want to call SetTypeOfNode with the intention to cast to LeafList
SetTypeOfNode(yangnodes[i]);
}
}
}
private static void SetTypeOfNode(YangNode inputnode)
{
///Desired
//Replace GIVENANYCLASSNAME with any given classname as parameter
//((GIVENANYCLASSNAME)inputnode).Type = "value";
((Leaf)inputnode).Type = "value";
}
/// <summary>
/// It is 100% guaranteed that the item is a Leaf.
/// </summary>
private static bool IsLeaf(int index)
{
return index == 0;
}
private static bool IsLeafList(int index)
{
return index == 1;
}
}
}
In the function "private static void SetTypeOfNode(YangNode inputnode)" I want to be able to give a Class as parameter what to cast to. In order to spare 100+ line in my actual program of casting like:
((Leaf)inputnode).Type = "value";
((LeafList)inputnode).Type = "value";
((AnothertypeInheritedfromYangnode)inputnode).Type = "value";
((AnothertypeInheritedfromYangnode2)inputnode).Type = "value";
...
How can you pass a Classname as parameter that can be given into the casting parameter?

Related

Property or indexer must have at least one accessor

I'm learning C#, trying to get to grips with accessors at the moment.
I'm going nuts looking at this, I have no idea what I've done wrong:
class BankAccount
{
// *PROPERTIES*
private int _initialDeposit = 0;
// **ACCESSORS**
public int SavingsAccount
{
set
{
_initialDeposit = value;
}
get
{
return _initialDeposit;
}
}
}
The Form looks like this:
public partial class BankForm : Form
{
private BankAccount _myAccount;
public BankForm()
{
InitializeComponent();
_myAccount = new BankAccount();
}
private void initialDepositButton_Click(object sender, EventArgs e)
{
_myAccount.SavingsAccount = Convert.ToInt32(initialDepositTextBox.Text);
bankAccountListBox.Text = "Account opened with initial Deposit " + initialDepositTextBox.Text;
}
}
But I get this error:
Property or indexer must have at least one accessor
I'm not getting any errors. Move location of private BankAccount _myAccount;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace BankForm
{
public partial class BankForm : Form
{
public BankForm()
{
InitializeComponent();
_myAccount = new BankAccount();
}
private BankAccount _myAccount;
private void initialDepositButton_Click(object sender, EventArgs e)
{
_myAccount.SavingsAccount = Convert.ToInt32(initialDepositTextBox.Text);
bankAccountListBox.Text = "Account opened with initial Deposit " + initialDepositTextBox.Text;
}
}
class BankAccount
{
// *PROPERTIES*
private int _initialDeposit = 0;
// **ACCESSORS**
public int SavingsAccount
{
set
{
_initialDeposit = value;
}
get
{
return _initialDeposit;
}
}
}
}
​

Use a class in two different namespace

How do use a class from namespace in other namespace?
namespace All
{
class X
{
public static void Read() {}
}
class Y
{
public static void Write() {}
}
}
namespace A
{
namespace First{
//use class X in namespace All here;
}
}
namespace B
{
namespace Second{
//use class Y in namespace All here;
}
}
i don't want copy paste code,is there a keyword in C# to reference the hole the class? use it here like
B.Second.Y.Write();
you cannot directly use other types as variable in a namespace
So
You may use those types (X, Y) in the types in those namespaces (First, Second). e.g
namespace All
{
class X
{
public static void Read() { }
}
class Y
{
public static void Write() { }
}
}
namespace A
{
namespace First
{
//use class X in namespace All here;
}
}
namespace B
{
namespace Second
{
//use class Y in namespace All here;
class MyClass
{
private All.X; //HERE is the code
}
}
}
Try the using Keyword
using A;
using B;
using All;
If you define namespace A & B as followed:
namespace All
{
public class X
{
public static void Read() { }
}
public class Y
{
public static void Write() { }
}
}
namespace A
{
namespace First
{
public static class X
{
public static void Read()
{
All.X.Read();
}
}
}
}
namespace B
{
namespace Second
{
public static class Y
{
public static void Write()
{
All.Y.Write();
}
}
}
}
You can then use it like so...
namespace CodeResearch.StackOverFlowTests
{
using System;
/// <summary>
/// Defines DebugStackOverFlow type
/// </summary>
public class DebugStackOverFlow
{
/// <summary>
/// Tests debugging StackOverFlow questions
/// </summary>
public static void Test()
{
A.First.X.Read();
B.Second.Y.Write();
Console.ReadLine();
}
}
}
NOTE:
I have all of this defined in the same cs file.

Updating a Control Within a Currently Open Form

I am writing a C# Application where I can add various types of students - a normal student, or a academic society student, or a arts and culture society student. On the main form, I have 3 data grids (one lists academic students, one list arts and culture students, and the other lists the normal students). For the user to specify additional information about a student (should they be an academic society student, or an arts and culture student, or both), another form will open up asking the user to add additional Information.
After the information has been specified, I would like to take that information, and add it to the relevant data grid, in other words, update the data grid in the main form.
How I thought I would tackle this idea:
Create a method in the main form to add a new entry to the data grid
Save the main form object into a Form object
Have a method which will will add a new row of data into the form object mentioned in step 2
Update the currently open main form with the form object I had saved.
I tried doing the above, and I get the error:
Error 1 Inconsistent accessibility: parameter type 'ONT2000_Practical_05.AcademicSocieties' is less accessible than method 'ONT2000_Practical_05.Form1.addAcademicStudentRow(ONT2000_Practical_05.AcademicSocieties)' c:\users\okuhle\documents\visual studio 2013\Projects\ONT2000 Practical 05\ONT2000 Practical 05\Form1.cs 35 21 ONT2000 Practical 05
I have 3 classes - AcademicSocieties, ArtsAndCultureSociety and Student...both AcademicSocieties and ArtsAndCultureSociety inherit the Student class. Below is the code for the classes:
THE STUDENT CLASS:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ONT2000_Practical_05
{
public class Student
{
private String studentNumber;
private String studentName;
private String studentDegree;
public Student(string number, string name, string degree)
{
studentNumber = number;
studentName = name;
studentDegree = degree;
}
public String getStudentName()
{
return studentName;
}
public String getStudentNumber()
{
return studentNumber;
}
public String getStudentDegree()
{
return studentDegree;
}
}
}
THE ACADEMICSSOCIETY CLASS:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ONT2000_Practical_05
{
public class AcademicSocieties : Student
{
private String courseCode;
private String societyName;
public AcademicSocieties(String studentName, String studentNumber, String studentDegree, String courseCode, String societyName) : base(studentNumber, studentName, studentDegree)
{
this.courseCode = courseCode;
this.societyName = societyName;
}
public String getCourseCode()
{
return courseCode;
}
public String getSocietyName()
{
return societyName;
}
}
}
THE ARTSANDCULTURE SOCIETY CLASS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ONT2000_Practical_05
{
class ArtsAndCultureSociety : Student
{
private int experienceLevel;
private int competitionWins;
private String societyName;
private Boolean colours;
public ArtsAndCultureSociety(int level, int wins, string societyName, String studentNumber, String studentName, String studentDegree) : base(studentNumber, studentName, studentDegree)
{
experienceLevel = level;
competitionWins = wins;
this.societyName = societyName;
}
}
}
THE MAIN FORM:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ONT2000_Practical_05
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void academicSocietiesToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void degreeLabel_Click(object sender, EventArgs e)
{
}
private void exitApplicationToolStripMenuItem_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
public void addAcademicStudentRow(AcademicSocieties thisStudent) //This is where the Error Occurs
{
academicSocietiesDataGrid.Rows.Add(thisStudent.getStudentName(), thisStudent.getSocietyName(), thisStudent.getCourseCode());
}
private void addStudentButton_Click(object sender, EventArgs e)
{
String studentName = ProgramFunctions.validateTextBoxData(studentNameTextBox);
String studentNumber = ProgramFunctions.validateStudentNumber(studentNumberTextBox);
String studentDegree = ProgramFunctions.validateTextBoxData(degreeTextBox);
if (studentName.Equals(null) || studentNumber.Equals(null) || studentDegree.Equals(null) || studentDegree.Equals("null")) //Error 1 is on this line
{
ProgramFunctions.displayMessage("Data Integrity Error", "As a result of one or more fields failing data validation, this application will not continue processing data");
} else
{
if (artsAndCultureCheckBox.Checked && academicCheckBox.Checked)
{
Student newStudent = new Student(studentNumber, studentName, studentDegree);
StudentData.setCurrentStudent(newStudent);
ProgramFunctions.saveCurrentForm(this);
GeneralStudentSocietyForm generalForm = new GeneralStudentSocietyForm();
generalForm.Visible = true;
generalForm.Focus();
} else if (academicCheckBox.Checked)
{
Student newStudent = new Student(studentNumber, studentName, studentDegree);
StudentData.setCurrentStudent(newStudent);
ProgramFunctions.saveCurrentForm(this);
AcademicSocietyForm academics = new AcademicSocietyForm();
academics.Visible = true;
academics.Focus();
} else if (artsAndCultureCheckBox.Checked)
{
Student newStudent = new Student(studentNumber, studentName, studentDegree);
StudentData.setCurrentStudent(newStudent);
ProgramFunctions.saveCurrentForm(this);
ArtsAndCultureForm artsAndCulture = new ArtsAndCultureForm();
artsAndCulture.Visible = true;
artsAndCulture.Focus();
} else
{
Student newStudent = new Student(studentNumber, studentName, studentDegree);
StudentData.addNewStudent(newStudent);
ProgramFunctions.displayMessage("Student Added", "A New Student has successfully been added to the database. Click OK to continue");
studentDataDataGird.Rows.Add(newStudent.getStudentName(), newStudent.getStudentNumber(), newStudent.getStudentDegree());
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
ProgramFunctions.addNewAcademicSociety("Accounting Society");
ProgramFunctions.addNewAcademicSociety("Law Student Society");
ProgramFunctions.addNewAcademicSociety("Science Student Society");
ProgramFunctions.addNewAcademicSociety("Information Technology Student Society");
ProgramFunctions.addNewAcademicSociety("Business Science Student Society");
ProgramFunctions.addNewArtsAndCultureSociety("Choir Society");
ProgramFunctions.addNewArtsAndCultureSociety("Hip Hop Society");
ProgramFunctions.addNewArtsAndCultureSociety("Anime Society");
ProgramFunctions.addNewArtsAndCultureSociety("The Hockey Society");
}
private void studentDataDataGird_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
public void academicSocietiesDataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
THE PROGRAMFUNCTIONS Class (This is where I am saving the Form Object):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ONT2000_Practical_05
{
class ProgramFunctions
{
private static List<String> academicSocieties = new List<String>();
private static List<String> artsAndCultureSocieties = new List<String>();
private static Form1 formObject;
public static void saveCurrentForm(Form1 formData)
{
formObject = formData;
}
public static void academicStudentDataGridRow(AcademicSocieties newStudent)
{
formObject.addAcademicStudentRow(newStudent);
}
public static Form1 updateMainForm()
{
return formObject;
}
public static void addNewAcademicSociety(String societyName)
{
academicSocieties.Add(societyName);
}
public static void addNewArtsAndCultureSociety(String societyName)
{
artsAndCultureSocieties.Add(societyName);
}
public static void displayMessage(String title, String Message)
{
MessageBox.Show(Message, title);
}
public static String validateTextBoxData(TextBox thisTextBox)
{
if (thisTextBox.Text.Equals(null) || thisTextBox.Text.Equals("") || thisTextBox.Text.Equals(" "))
{
displayMessage("Empty Data Detected!", "You may not specify empty data for the student");
return null;
} else
{
thisTextBox.Text = thisTextBox.Text.Trim();
thisTextBox.Text = thisTextBox.Text.ToUpper();
return thisTextBox.Text;
}
}
public static String getSelectedItem(ComboBox thisComboBox)
{
return thisComboBox.SelectedItem.ToString();
}
public static int getArtsAndCultureCount()
{
return artsAndCultureSocieties.Count;
}
public static int getAcademicSocietyCount()
{
return academicSocieties.Count;
}
public static String getAcademicSociety(int index)
{
return academicSocieties[index];
}
public static String getArtsAndCultureSociety(int index)
{
return artsAndCultureSocieties[index];
}
public static String validateStudentNumber(TextBox studentNumberTextBox)
{
if (studentNumberTextBox.Text.Equals(null) || studentNumberTextBox.Text.Equals("") || studentNumberTextBox.Text.Equals(" "))
{
displayMessage("Empty Data Detected!", "You did not input any data...Please be sure you do specify some data");
return null;
} else
{
if (!studentNumberTextBox.Text.StartsWith("s"))
{
displayMessage("Invalid Student Number", "You have entered an invalid student number. Please be sure this student number follows the correct format. The student number must begin with a 's' character. ");
return null;
}
if (studentNumberTextBox.Text.Length != 10)
{
displayMessage("Invalid Student Number", "The student number specified may not be longer than 10 characters");
return null;
}
return studentNumberTextBox.Text;
}
}
}
}
change the access modifier of the class ProgramFunctions,ArtsAndCultureSociety to public.
Could it be you are missing the access modifier 'public' in some of your class definitions? If you don't add public before ArtsAndCultureSociety, it will be private.

Web User Control Collection data is not storing

I wanted to create a web control which has collection featured in the ASPX. I have code below which has a problem.
I seem to turn off and objects collection editor(collection stable).But I object design information Design Time at runtime what you can not get
when I turn off the project.So in a way the information will be saved during design is disappear.
When I open the project files in aspx file nor what. Designer.cs do not coincide in any record in the file.
I want to show in the picture below, this situation partially.
Based on the above, or as seen in the example in asp.net collection listing on sample collection can fix or waiting for your advice.
Here is code
//******************************************************Rol.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SANNET.ToolBox.TemelRoller
{/*
[ControlBuilder(typeof(ListItemControlBuilder))]
[ParseChildren(true, "Text")]*/
[TypeConverter(typeof(ExpandableObjectConverter))]
public class Rol
{
private string rolAdi;
private AksiyonTuru aksiyonIcinKullan;
private EfektTuru iseYapilacak;
private string hataMesaji;
private IOzelEfekt ozelEfekt;
public String RolAdi { get { return rolAdi; } set { rolAdi = value; } }
public AksiyonTuru AksiyonIcinKullan { get { return aksiyonIcinKullan; } set { aksiyonIcinKullan = value; } }
public EfektTuru IseYapilacak { get { return iseYapilacak; } set { iseYapilacak = value; } }
public String HataMesaji { get { return hataMesaji; } set { hataMesaji = value; } }
public IOzelEfekt OzelEfekt { get { return ozelEfekt; } set { ozelEfekt = value; } }
public Rol()
{
RolAdi = "Hicbiri";
}
/*
public string GetAttribute(string key)
{
return (String)ViewState[key];
}
public void SetAttribute(string key, string value)
{
ViewState[key] = value;
}*/
}
}
//******************************************************RolListesi.cs
using SANNET.ToolBox.Yardimcilar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing.Design;
using System.Web.UI;
namespace SANNET.ToolBox.TemelRoller
{
//[TypeConverterAttribute(typeof(System.ComponentModel.ExpandableObjectConverter))]
[TypeConverterAttribute(typeof(System.ComponentModel.ExpandableObjectConverter))]
public class RolListesi : CollectionBase//ICollection<Rol>
{
private Collection<Rol> roller;
private Control parent;
public RolListesi(Control parent)
{
this.parent = parent;
parent.PreRender += parent_PreRender;
parent.Load += parent_PreRender;
roller = new Collection<Rol>();
}
void parent_PreRender(object sender, EventArgs e)
{
RolIslemleri.PreRenderIsle((Control)sender, this);
}
public Control Parent { get { return this.parent; } }
public Rol rolGetir(String rolAdi)
{
foreach (Rol r in roller) {
if (r.RolAdi.Equals(rolAdi))
return r;
}
return null;
}
public bool Contains(String rolAdi)
{
return rolGetir(rolAdi) != null;
}
public Rol this[int index]
{
get { return (Rol)roller[index]; }
}
public void Add(Rol emp)
{
roller.Add(emp);
}
public void Remove(Rol emp)
{
roller.Remove(emp);
}
}
}
//******************************************************RolCollectionEditor.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SANNET.ToolBox.TemelRoller
{
public class RolCollectionEditor : CollectionEditor
{
public RolCollectionEditor(Type type)
: base(type)
{
}
protected override string GetDisplayText(object value)
{
Rol item = new Rol();
item = (Rol)value;
return base.GetDisplayText(string.Format("{0}, {1}", item.RolAdi,
item.AksiyonIcinKullan));
}
}
}
//******************************************************SANButton.cs
using DevExpress.Web.ASPxEditors;
using SANNET.ToolBox.TemelRoller;
using System.ComponentModel;
using System.Web.UI;
namespace SANNET.ToolBox.Bilesenler
{
public class SANButton : ASPxButton, IRolSahibi
{
private RolListesi roller;
/* [Editor(typeof(System.ComponentModel.Design.CollectionEditor),
typeof(System.Drawing.Design.UITypeEditor))]*/
[Editor(typeof(RolCollectionEditor),
typeof(System.Drawing.Design.UITypeEditor))]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public RolListesi Roller { get {
if (roller == null)
{
roller = new RolListesi(this);
}
return roller; } }
}
}
The answer is
[PersistenceMode(PersistenceMode.InnerProperty)]
Here is sample usage
private Roller roller;
[Editor(typeof(RolCollectionEditor), typeof(System.Drawing.Design.UITypeEditor))]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[PersistenceMode(PersistenceMode.InnerProperty)]
public Roller Roller
{
get
{
if (roller == null)
{
roller = new Roller();
} return roller;
}
}

C#: Access Enum from another class

I know I can put my enum at the Namespace area of a class so everyone can access it being in the same namespace.
// defined in class2
public enum Mode { Selected, New, }
What I want is to access this enum from
public class1
{
var class2 = new class2();
// Set the Mode
class2.Mode = Model.Selected
}
Is this somehow possible without using namespace area?
You can declare an enum outside of a class:
namespace MyNamespace
{
public enum MyEnum
{
Entry1,
Entry2,
}
}
And then you can add using MyNamespace; where it needs to be used.
Aaron's answer is very nice but I believe there is a much better way to do this:
public static class class1
{
public void Run()
{
class2.Mode mode = class2.Mode.Selected;
if (mode == class2.Mode.Selected)
{
// Do something crazy here...
}
}
}
public static class class2
{
public enum Mode
{
Selected,
New
}
}
No point over complicating this. It is a simple task.
All the Best
Chris.
If you are trying to do what is described below it will not work...
public class MyClass1
{
private enum Mode { New, Selected };
public Mode ModeProperty { get; set; }
}
public class MyClass2
{
public MyClass2()
{
var myClass1 = new MyClass1();
//this will not work due to protection level
myClass1.ModeProperty = MyClass1.Mode.
}
}
What you could do however is below, which will work...
public interface IEnums
{
public enum Mode { New, Selected };
}
public class MyClass1
{
public IEnums.Mode ModeProperty { get; set; }
}
public class MyClass2
{
public MyClass2()
{
var myClass1 = new MyClass1();
//this will work
myClass1.ModeProperty = IEnums.Mode.New;
}
}
Yes:
class2.Mode = class2.Mode.Selected
But note that you can't have a nested type defined that has the same name as one of the outer class' members, so this code will not compile. Either the enum or the property will need to be named something else. Your class name and variable name conflict too, making this a bit more complex.
To make this a more generic answer, if you have this:
public class Foo
{
public SomeEnum SomeProperty { get; set; }
public enum SomeEnum {
Hello, World
}
}
Then this code will assign an enum value to the property:
Foo foo = new Foo();
foo.SomeProperty = Foo.SomeEnum.Hello;
I ended up solving my issue by changing it to a namespace accessor, found by utilizing Intellisense. I thought the enum was in the class, not just the namespace. If it was in the class, I would recommend moving it out of the class.
namespace ABC.XYZ.Contracts
{
public class ChangeOrder : BaseEntity, IAuditable
{
...
}
public enum ContractorSignatureType
{
A,
B,
V
}
}
ContractorSignatureType = Contracts.ContractorSignatureType.B,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace #enum
{
class temp
{
public enum names
{
mohitt,
keval,
Harshal,
nikk
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine((int)temp.names.nikk);
Console.ReadKey();
}
}
}
//by using this you can access the value of enum.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace #enum
{
class temp
{
public enum names
{
mohitt,
keval,
Harshal,
nikk
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(temp.names.nikk);
Console.ReadKey();
}
}
}

Categories

Resources