I'm new to programming and C#; I don't quite understand how to pass arguments with structs and could use some help in getting this code to work..
I'm making a program to test working with structs & methods.
I'm trying to make two methods..
My displayStudent() method is supposed to take the Student type parameters from the newStudent object/instance created by the CreateStudent_Click.
CreateStudent_Click() Method grabs the user input from three TextBoxes(nameOfStudent, studentID, studentsMajor) and concatenates them to be one string(Output) which is displayed on a fourth outputTextBox after the mouse click on Create Student button.
Myy CreateStudent_Click(), is supposed to get the user input and put it into a new object/instance of Student type as well as pass an argument to DisplayStudent(newStudent) as well as call it.
Any help you can provide would be very much appreciated. Thank you.
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 Student_Structure
{
struct Student
{
public string name;
public string studentID;
public string major;
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
private void displayStudent(ref Student student)
{
try
{
student.name = nameTextBox.Text;
student.studentID = studentIDTextBox.Text;
student.major = majorTextBox.Text;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void CreateStudent_Click(object sender, EventArgs e)
{
// Declare a string to hold a line of output.
string output;
// Create an instance of student.
Student newStudent = new Student();
newStudent.name = nameTextBox.Text;
newStudent.studentID = studentIDTextBox.Text;
newStudent.major = majorTextBox.Text;
// Clear the TextBoxes
nameTextBox.Clear();
studentIDTextBox.Clear();
majorTextBox.Clear();
displayStudent(Student.newStudent());
// Clear the TextBox's current contents.
foreach (Student student in newStudent)
{
}
}
}
Firstly (and this is just a rule of thumb) structs should be Immutable. Now there is 1000's of blogs on the internet that debate this and why and its best to read up on this.
However, by default they are mutable. Yet on saying that, there are a lot of mutable structs used in the framework like Point, Size, Rectangle. These structs are fully mutable. This is done (against the guidelines) for the sake of performance, as it avoids the need to create new values for modification operations.
...All that aside, if you are passing a mutable struct in a parameter (unlike a reference type) what you get is a copy. Nothing you do will make any difference unless you pass by ref.
Given a Mutable struct
public struct Student
{
public Student(string name, int studentId, string major)
{
Name = name;
StudentId = studentId;
Major = major;
}
public string Name { get; set; }
public int StudentId { get; set; }
public string Major { get; set; }
public override string ToString() => Name + ", " + StudentId + ", " + Major;
}
You can simply pass by reference
private void MutateStudent(ref Student student)
{
student.Name = "asd";
student.StudentId = 234;
student.Major = "ertyt";
}
or
private Student AbetterMutateStudent(Student student)
{
// this is actually a copy
student.Name = "asd";
student.StudentId = 234;
student.Major = "ertyt";
return student;
}
Example
var student = new Student("SomeName",1,"SomeMajor");
Console.WriteLine(student);
MutateStudent(ref student);
Console.WriteLine(student);
var student2 = AbetterMutateStudent(student);
Console.WriteLine(student2);
Output
SomeName, 1, SomeMajor
ByrRefName, 2, ByrRefMajor
ByCopyName, 3, ByCopyMajor
Related
I am trying to display the details of the movie but I am getting StackOverFlow exception in cast class where I am returning actorNames array.
I am trying to make the movie object. In movie object, I am creating objects for Cast and Genre class and passing them in movie class constructor with the data.
Kindly let me know how I can correct this issue. This issue might exist for Genre class as well. Please let me know if there is any case like that as well.
// Genre Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_4
{
class Genre
{
private static Dictionary<string, string> genre = new Dictionary<string, string>();
public string[] genreName { get { return genreName; } set { } }
public string[] genreDescription { get { return genreDescription; } }
public Genre() {
setGlobalGenreDictionary();
}
public Genre(string[] nameOfGenre) {
this.genreName = nameOfGenre;
setGenreDecsription(nameOfGenre);
}
public void setGenreDecsription(string[] genreName) {
int i = 0;
foreach(KeyValuePair<string, string> gen in genre) {
if (gen.Key == genreName[i]) {
genreDescription[i] = gen.Value;
}
i++;
}
}
public void setGlobalGenreDictionary() {
genre.Add("Action", "Associated with particular types of spectacle (e.g., explosions, chases, combat)");
genre.Add("Adventure", "Implies a narrative that is defined by a journey (often including some form of pursuit) and is usually located within a fantasy or exoticized setting. Typically, though not always, such stories include the quest narrative. The predominant emphasis on violence and fighting in action films is the typical difference between the two genres.");
genre.Add("Animation", "A film medium in which the film's images are primarily created by computer or hand and the characters are voiced by actors. Animation can otherwise incorporate any genre and subgenre and is often confused as a genre itself");
genre.Add("Comedy", "Defined by events that are primarily intended to make the audience laugh");
genre.Add("Drama", "Focused on emotions and defined by conflict, often looking to reality rather than sensationalism.");
genre.Add("Fantasy", "Films defined by situations that transcend natural laws and/or by settings inside a fictional universe, with narratives that are often inspired by or involve human myths. The genre typically incorporates non-scientific concepts such as magic, mythical creatures, and supernatural elements.");
genre.Add("History", "Films that either provide more-or-less accurate representations of historical accounts or depict fictional narratives placed inside an accurate depiction of a historical setting.");
genre.Add("Horror", "Films that seek to elicit fear or disgust in the audience for entertainment purposes.");
genre.Add("Noir", "A genre of stylish crime dramas particularly popular during the 1940s and '50s. They were often reflective of the American society and culture at the time.");
genre.Add("Science Fiction", "Films are defined by a combination of imaginative speculation and a scientific or technological premise, making use of the changes and trajectory of technology and science. This genre often incorporates space, biology, energy, time, and any other observable science.");
genre.Add("Thriller", "Films that evoke excitement and suspense in the audience. The suspense element found in most films' plots is particularly exploited by the filmmaker in this genre. Tension is created by delaying what the audience sees as inevitable, and is built through situations that are menacing or where escape seems impossible.");
genre.Add("Western", "A genre in which films are set in the American West during the 19th century and embodies the \"spirit, the struggle and the demise of the new frontier.\" These films will often feature horse riding, violent and non-violent interaction with Native-American tribes, gunfights, and technology created during the industrial revolution.");
}
}
}
//Movie Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_4
{
class Movie
{
int movieId;
string movieTitle;
string storyline;
double rating;
int year;
Cast cast;
Genre genre;
public Movie(int id, string title, string story, double rating, int yr, Cast castObj, Genre genObj) {
movieId = id;
movieTitle = title;
storyline = story;
this.rating = rating;
year = yr;
this.cast = castObj;
this.genre = genObj;
}
public void getMovie() {
Console.WriteLine("Movie:" + this.movieTitle + "\n"
+ "Year:" + this.year + "\n"
+ "IMDB Rating:" + this.rating + "/10\n "
+ "Storyline:" + this.storyline );
Console.WriteLine("Cast:");
try
{
int noOfMembers = this.cast.actorNames.Length;
for (int i = 0; i < noOfMembers; i++)
{
Console.WriteLine(cast.roles + ":" + cast.actorNames);
}
}
catch (Exception e)
{
Console.WriteLine(e.GetType());
}
int noOfGenres = this.genre.genreName.Length;
for (int i = 0; i < noOfGenres; i++)
{
Console.WriteLine(this.genre.genreName + ":" + this.genre.genreDescription);
}
}
}
}
//Cast Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_4
{
class Cast
{
public string[] actorNames {
get
{
return actorNames;
}
set { } }
public string[] roles { get { return roles; } set { } }
int referenceToMovie;
public Cast(string[] actorNames, string[] roles, int reference) {
this.actorNames = actorNames;
this.roles = roles;
this.referenceToMovie = reference;
}
}
}
//Main Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_4
{
class Program
{
static void Main(string[] args)
{
string castNames = "Kenneth Branagh,Patrick Doyle,Chris Hemsworth,Natalie Portman";
string castRoles = "Director,Music,Actor,Actor";
string genresOfTheMovie = "Action,Adventure,Fantasy";
Movie thor = new Movie(0800369, "Thor", "The powerful but arrogant god Thor is cast out of Asgard to live amongst humans in Midgard (Earth), " +
"where he soon becomes one of their finest defenders.", 7.0, 2011, new Cast(castNames.Split(','), castRoles.Split(','), 0800369), new Genre(genresOfTheMovie.Split(',')));
thor.getMovie();
//Movie ironman = new Movie();
//Movie hulk = new Movie();
//Movie avengers = new Movie();
//Movie blackPanther = new Movie();
}
}
}
There are many issues with your code:
Genre:
you set a global genre Dictionary on every initialization of Genre. This means you'll be adding all of the items every time Genre you try to create a Genre.
private static Dictionary<string, string> genre = new Dictionary<string, string>();
//make this static
public static void SetGlobalGenreDictionary()
and then call it
Genre.SetGlobalGenreDictionary();
in your program
For your properties, they are what is causing your StackOverflow issue.
There are a couple of ways to write these, but your version will keep calling itself causing the stack overflow.
//Option 1:
public string[] GenreName1 { get; set; }
//Option 2:
private string[] genreName2;
public string[] GenreName2 {
get
{
return genreName2;
}
set
{
//you have to write a Set method body if you write a get method. Otherwise nothing will happen. If you don't want to set it, don't write a set method at all.
genreName2 = value;
}
}
There are other issues, but this should get you started on your homework problem.
Step 1: I have created a C# application called : Student details
Step 2: Added four TextBoxes and named them as :
Image below to refer:
Studentname.Text
StudentSurname.Text
StudentCity.Text
StudentState.Text
DATA INSIDE CSV FILE
vikas,gadhi,mumbai,maharashtra
prem,yogi,kolkata,maha
roja,goal,orissa,oya
ram,kala,goa,barka
Issue is How do I fetch all the data(surname,city,state) of user prem into above textboxes studentsurname,studentcity,studentstate from csv file when I search the name in textbox 1 => studentname.Text as prem
Below is the Code where I am stuck at return null and code inside Load_Script_Click
void Connection_fetch_details(String searchName)
{
var strLines = File.ReadLines(filePath);
foreach (var line in strLines)
{
if (line.Split(',')[0].Equals(searchName))
{
Connection_fetch_details cd = new Connection_fetch_details()
{
username = line.Split(',')[1]
};
}
}
return;
}
private void Load_Script_Click(object sender, EventArgs e)
{
// load script is button
String con_env = textenv.Text.ToString();
//Address Address = GetAddress("vikas");
//textsurname.text = Address.Surname
Connection_fetch_details cd = Connection_fetch_details(con_env);
textusername.Text = cd.username;
}
==============================================================
Class file name : Address.class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DDL_SCRIPT_GENERATOR
{
public class Connection_fetch_details
{
public string username { get; set; }
}
}
The main problem is that your method is void, which means it doesn't return any value. So even though you may be finding a match, and creating a Connection_fetch_details object, you aren't returning that result back to the calling method.
This will fix that problem:
Connection_fetch_details Connection_fetch_details(String searchName)
{
var strLines = File.ReadLines(filePath);
foreach (var line in strLines)
{
if (line.Split(',')[0].Equals(searchName))
{
Connection_fetch_details cd = new Connection_fetch_details()
{
username = line.Split(',')[1]
};
return cd; //return the object containing the matched username
}
}
return null;
}
Now it will return a Connection_fetch_details object if there is a match, or null if there is no match.
Next, you asked about returning all the fields, not just one. For that you would need to
a) add more properties to your object
b) add more code to populate those properties from the CSV
c) add code to populate the textboxes with the results from the object.
I'm also going to rename "username" to something more relevant, since none of the field names you described in the question match that. I'm also going to rename your class to "Student", and rename your search method, for the same reason.
Here's an example:
Student searchStudent(String searchName)
{
var strLines = File.ReadLines(filePath);
foreach (var line in strLines)
{
var split = line.Split(',');
if (split[0].Equals(searchName))
{
Student s = new Student()
{
firstname = searchName,
surname = split[1],
city = split[2],
state = split[3]
};
return s; //return the object containing the matched name
}
}
return null;
}
private void Load_Script_Click(object sender, EventArgs e)
{
// load script is button
String con_env = textenv.Text.ToString();
//Address Address = GetAddress("vikas");
//textsurname.text = Address.Surname
Student st = searchStudent(con_env);
textsurname.Text = st.surname;
txtcity.Text = st.city;
txtstate.Text = st.state;
}
namespace DDL_SCRIPT_GENERATOR
{
public class Student
{
public string firstname { get; set; }
public string surname { get; set; }
public string city { get; set; }
public string state { get; set; }
}
}
To accomplish your goal you have to further separate your problem in more granular steps and also distinguish between what you show in your UI and what informations you hold in the background in which format.
Create a class with the desired properties
public class Student { public string Name { get; set; } ... }
Learn how to read a csv file into such an object by using an existing library like CsvHelper or CsvReader.
When you have something like List<Student> from this part. Learn how you can visualize such a thing by using some Binding (also depends on the visualization you use Winforms, WPF, etc.).
Depending on the visualization component it already supports filtering or you need to filter by yourself by using e.g. LINQ to get the matching elements students.Where(student => student.Name.StartsWith(search)).
So far a lot of smaller problems which is simply to much to answer in a single one. Please try to break down your problems into smaller ones and search for their solutions. If you get stuck, ask a new question. That's all I can do for you now.
There are semi answer to this question which I have read through thoroughly, as well as all things MSDN about generic classes but I am still having trouble when a generic class inherits from another class: where T: ClassName
For example, here is my generic list class
public class MyGenericList2<T> where T : Person
{
private T[] list;
public MyGenericList2(int size)
{
list = new T[size];
}
public T getItem(int index)
{
T temp = default(T);
temp = list[index];
return temp;
}
public void setItem(int index, T value)
{
list[index] = value;
}
public void DisplayList()
{
for (int i = 0; i < list.Length; i++)
{
Console.Out.WriteLine(list[i]);
}
}
}
It inherits from the person class:
NOTE: It is shortened for clarity sake
public abstract class Person
{
protected string firstName;
// Getters
public string getFirstName()
{
return this.firstName;
}
public void setFirstName(string fname)
{
this.firstName = fname;
}
}
When I try to call it I get an error about trying to convert a string to a {namespace}.Person which I sort of get, in that I am trying to put a string into a 'Person' box, but how does one call the class using this mechanism?
Here is the main method
public static void Main(string[] args)
{
MyGenericList2<Person> studentGeneric = new MyGenericList2<Person>(3);
Student st1 = new Student();
st1.setFirstName("Thor");
studentGeneric.setItem(0, st1); //This does not work
studentGeneric.setItem(1, Person.setFirstName("Odin"); // Does not work
studentGeneric.setItem(2, st1.setFirstName("Slepnir"); // Does not work
studentGeneric.DisplayList();
Console.ReadLine();
}
If I cut out the Where T : Person and use GenericList2<string> it works fine, which makes sense since it is string to string.
Any help would be appreciated
quick clarification Student inherits from Person:
public class Student : Person
{
// Student 1
private string studentID01 = "001";
public string getStudentID01()
{
return this.studentID01;
}
}
First of all I would recommend using public properties for your classes, for example:
public abstract class Person
{
public string FirstName { get; set; }
}
public class Student : Person
{
public string StudentId { get; set; }
}
This means your list code would work like this:
Student st1 = new Student();
st1.FirstName = "Thor";
studentGeneric.setItem(0, st1);
And you can even use this syntax:
studentGeneric.setItem(1, new Student
{
FirstName = "Odin"
});
Additionally, the .Net Framework already provides a really nice set of generic collection classes you can use so you don't really need your MyGenericList2<T> class. For example, the most commonly used class is System.Collections.Generic.List:
var people = new System.Collections.Generic.List<Person>();
people.Add(new Student
{
FirstName = "Odin"
});
Or even using the collection initialiser syntax:
var people = new System.Collections.Generic.List<Person>
{
new Student
{
FirstName = "Odin"
}
});
Finally, the problem you are having with outputting your values to the console is because C# doesn't know what to do with your class so by default outputs the value of student.ToString(). And becaue you haven't told your class what to do with it, it just outputs the name of the type. You can either override ToString or, much simpler just call the getFirstName() method:
Console.WriteLine(list[i].getFirstName());
You are using setItem incorrectly. This method can be used to set the value of elements in the list array in an instance of MyGenericList2 class.
To use the setFirstName method on an instance of the Student class, first use getItem to return the object instance. For example:
public void Main(string[] args)
{
MyGenericList2<Person> studentGeneric = new MyGenericList2<Person>(3);
Student st1 = new Student();
st1.setFirstName("Thor");
studentGeneric.setItem(0, st1);
Student st2 = new Student();
studentGeneric.setItem(1, st2);
studentGeneric.getItem(1).setFirstName("Odin");
Student st3 = new Student();
studentGeneric.setItem(2, st3);
studentGeneric.getItem(2).setFirstName("Slepnir");
studentGeneric.DisplayList();
Console.ReadLine();
}
To display the list contents correctly, replace your DisplayList() method with:
public void DisplayList()
{
for (int i = 0; i < list.Length; i++)
{
if(list[i] != null){
Console.Out.WriteLine("{0}: {1}", i, list[i].getFirstName());
}
else
{
Console.Out.WriteLine("{0}: [NULL]", i);
}
}
}
Edit to save you from reading through this whole post
tldr: an object's fields should not be static unless you want all instances of that object to have the same value for that field
I'm trying to create and populate an ArrayList of Blog objects. I do know the generic way do this:
create ArrayList of Blogs
loop (some condition)
create new Blog
add this Blog to AL
However, when I attempt to do so within the while(datareader.read()) loop, all of the elements in the ArrayList are exactly the same Blog. Specifically, I end up with an ArrayList filled with multiple pointers to the very last Blog object from the database table. Here is my code:
public static ArrayList AllBlogs()
{
SqlDataReader dr = anonPage.ExecuteReader("SELECT * FROM Kristina_Blogs");
ArrayList allBlogs = new ArrayList();
if (dr.HasRows)
{
while (dr.Read())
{
Blog b = new Blog();
//grab a row from Kristina_Blogs and assign those attributes to b
b.setTitle(dr["title"].ToString());
b.setMessage(dr["message"].ToString());
b.setId(dr["id"]);
allBlogs.Add(b);
}
}
dr.Close();
return allBlogs;
}
As I said before, the result of this is an ArrayList filled with pointers to the very last blog from the Kristina_Blogs table. I imagine the ArrayList allBlogs looks like [b, b, b, ... b] and therefore they ALL get updated when I say b.setTitle() etc. But how can this be the case if I am creating a NEW Blog object at the beginning of each iteration?
Here is some extra info that you don't have to read but it might clear up some confusion about the structure of the problem:
Blog object has id, title, and message fields and their respective getter/setters
Kristina_Blogs is a table representing these blogs with columns for id, title, message
The suggestions say to include a tag for my DB engine but I can't find a tag for it: Microsoft SQL Server Management Studio
This code works perfectly when I use an ArrayList of Strings instead of Blogs
Edit: Including the code from Blog class
public class Blog
{
public App myApp;
public static string Title;
public static string Message;
public static int Id;
//constructors
public Blog() { }
public Blog(App App) { this.myApp = App; }
//all getters and setters look like this
public string getTitle() { return Title; }
public void setTitle(string t) { Title = t; }
}
The main problem you have, as I mentioned in comments is your member variables are static, so when you set the value, they change in all instances. you should change your code this way:
public class Blog
{
public int Id { get; set; }
public string Title { get; set; }
public string Message { get; set; }
}
And fill your list this way, don't forget to add using System.Linq;:
var result = new List<Blog>();
var connection = #"your connection string";
var command = "SELECT * FROM Kristina_Blogs";
var adapter = new System.Data.SqlClient.SqlDataAdapter(command, connection);
var dataTable = new DataTable();
//Get data
adapter.Fill(dataTable);
dataTable.Rows.Cast<DataRow>().ToList()
.ForEach(row =>
{
var b = new Blog();
b.Id = row.Field<int>("Id");
b.Title = row.Field<string>("Title");
b.Message = row.Field<string>("Message");
result.Add(b);
});
return result;
Note:
When you create a member static, it is shared between all instances of that calss.
In C# you can use property to get or set values, you don't need to setX or setY, when you get the value of a property, the get code of that property will execute and when you assign a value to a property the set part of it will execute. you can define properties this way:
Property:
private int id;
public int Id
{
get
{
return id;
}
set
{
id = value;
}
}
or more simple:
public int Id { get; set; }
All of the fields in your Blog class are static, meaning they're shared between all object instances. You want them to be instance field (meaning not static) so that each object has its own copy of each of those values.
Remove the static attributes from your class:
public class Blog
{
public App myApp;
public String Title;
public String Message;
public int Id;
//constructors
public Blog() { }
public Blog(App App) { this.myApp = App; }
//all getters and setters look like this
public String getTitle() { return Title; }
public String getMessage() { return Message; }
public void setTitle(String t) { Title = t; }
public void setMessage(String m) { Message = m; }
}
When you use static variables, all instances of an object will contain the same values in those variables. By removing the static keyword, you are allowing different instances of the object to hold different values.
Now, every time you create a blog object, that object's Title and Message etc, will contain its own information.
I would make a quick method to prevent null value from throwing error
public static string GetSafeString(SqlDataReader reader, int index)
{
if (!reader.IsDBNull(index))
return reader.GetString(index);
else
return string.Empty;
}
Replace this code:
while (dr.Read())
{
Blog b = new Blog();
//grab a row from Kristina_Blogs and assign those attributes to b
b.setTitle(dr["title"].ToString());
b.setMessage(dr["message"].ToString());
b.setId(dr["id"]);
allBlogs.Add(b);
}
With This Code:
while (dr.Read())
{
Blog b = new Blog();
//grab a row from Kristina_Blogs and assign those attributes to b
b.setId(dr.GetInt32(0));
b.setTitle(GetSafeString(dr, 1);
b.setMessage(GetSafeString(dr, 2);
allBlogs.Add(b);
}
Where the number is the index of field in the record and assuming "id" is an integer. Also consider moving creation of "Blog" object outside of loop and just change values.
I'm doing a simple program to add a student(with ID,Name) to a List, then to search Student by ID through session.
Add Student Module is like below,
protected void addStudent(object sender, EventArgs e)
{
List<Student> thisstdlist = new List<Student>();
thisstdlist = (List<Student>)Session["stdlist"];
thisstdlist.Add(new Student(txtsid.Text,txtsname.Text));
Session["stdlist"] = thisstdlist;
Response.Redirect("Home.aspx");
}
Search Student Module is Like Below,
protected void searchStudent(object sender, EventArgs e)
{
foreach (Student element in (List<Student>)Session["stdlist"])
{
if(element.getID().Equals(txtstdid.Text)){
txtstdname.Text = element.getName();
}
}
}
Student Class is like below,
public class Student
{
private String Name;
private String ID;
public Student(String sid, String sn) {
this.Name = sn;
this.ID = sid;
}
public String getName() {
return this.Name;
}
public String getID()
{
return this.ID;
}
}
But when I added students, for ex: 100,John and Search by 100 it gives me no result. Please can anyone show me the mistake or the correct way of doing this.
are you setting breakpoints and actually checking what the values of these lists and what is actually stored in the session?
.Equals() is not doing what you think it is
try :
foreach (Student element in (List<Student>)Session["stdlist"])
{
if(element.ID == txtstdid.Text){
txtstdname.Text = element.getName();
}
}
The add Student module won't initialize the student list correctly - you are creating a new List<Student> and then throwing the new list away with the next line assignment. I would go with something like:
var thisstdlist = (List<Student>)Session["stdlist"];
// If a key isn't found in Session, it will be null ..
if (thisstdlist == null)
{
// i.e. only re-initialize if it was missing from session
thisstdlist = new List<Student>();
// You don't need to continually reassign the session variable
Session["stdlist"] = thisstdlist;
}
// Adds to the list; now that Session also has a reference to the same list
thisstdlist.Add(new Student(txtsid.Text,txtsname.Text));
As per the comment, note that c# has automatic (albeit mutable) properties - you don't need the Java-style getters and setters.
public class Student
{
public Student(string sid, string sn)
{
Name = sn;
ID = sid;
}
public string Name
{
get;
set;
}
public string ID
{
get;
set;
}
}
Also, in .Net, == for strings is overridden to test values (unlike Java's reference equality for strings), so you can rewrite the comparison as:
if (element.ID == txtstdid.Text)
{
txtstdname.Text = element.Name;
}
Re : foreach - I guess means that you are using the List in a Dictionary (HashMap) fashion - if you use Dictionary instead of List - this will allow you do remove the foreach in favour of:
// addStudent ...
var txtstdname = new Dictionary<string, Student>();
// ...
txtstdname.Add(txtsid.Text, new Student(txtsid.Text,txtsname.Text))
// searchStudent ...
Student element = null;
if (txtstdname.TryGetValue(out element))
{
txtstdname.Text = element.Name();
}