I'm trying to return an object in C#. In JavaScript, I would do this:
function myFunction () {
var myObj = { firstName: "John", lastName: "Smith", age: 20};
return myObj;
}
Everything I'm reading about returning an object within C# is much different than this so it's throwing me for a loop.
What I want to do is run a query to SQL to get some user info and return the users Role, Full Name, Email, etc...
Here is my current C# Code:
public static string getUserRole(string connectionString, string userId)
{
string role;
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlCommand sqlCom = new SqlCommand();
SqlDataReader reader;
sqlCom.CommandText = "SELECT Role FROM myDatabase.Table WHERE Email = '" + userId + "'";
sqlCom.CommandType = CommandType.Text;
sqlCom.Connection = sqlCon;
sqlCon.Open();
reader = sqlCom.ExecuteReader();
if (reader.Read())
{
role = reader.GetString(0);
sqlCon.Close();
return role;
}
else
{
return "An error has occurred";
}
}
I'm assuming I need to do something like the following but it doesn't work:
public static string getUserRole(string connectionString, string userId)
{
string role;
string fullName;
string email;
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlCommand sqlCom = new SqlCommand();
SqlDataReader reader;
sqlCom.CommandText = "SELECT Role FROM myDatabase.Table WHERE Email = '" + userId + "'";
sqlCom.CommandType = CommandType.Text;
sqlCom.Connection = sqlCon;
sqlCon.Open();
reader = sqlCom.ExecuteReader();
if (reader.Read())
{
public class myObject
{
role = reader.GetString(0);
fullName = reader.GetString(1);
email = reader.GetString(2);
}
sqlCon.Close();
return myObject;
}
else
{
return "An error has occurred";
}
}
I'm probably way off but from what I'm reading, object within c# are basically classes. So that makes sense. I need to create a class that defines my properties. Is this correct? I've ready lots of posts and watched some youtube videos but none are 'clicking'
Thanks in advance for any helpful input.