I am writing my first C# application, which in this case is just a “learning exercise” This example is a simplified block of code that I have used many times in VB.Net so I know that it works correctly. This is what the VB code looks like.
Public Class User
Private Const CN_LoginId As String = "Login"
Private Const CN_Password As String = "Password"
Private _password As String
Public Property Password() As String
Get
Return _password
End Get
Set(ByVal value As String)
_password = value
End Set
End Property
Public Shared Function Create(ByVal Login As String) As User
Dim usr = New User()
Using dt As DataTable = DAC.ExecuteDataTable("usp_PasswordSelect", _
DAC.Parameter(CN_LoginId, Login))
With dt.Rows(0)
usr.Password = CStr(.Item(CN_Password))
End With
End Using
Return usr
End Function
End Class
So in C# I have tried converting it by hand and by using Telerik’s online conversion utility, which is what I am posting below because I am assuming that it is closer to the right answer then what I did myself.
public class User
{
private const string CN_LoginId = "Login";
private const string CN_Password = "Password";
private string _password;
public string Password
{
get { return _password; }
set { _password = value; }
}
public static User Create(string Login)
{
object usr = new User();
using (DataTable dt = DAC.ExecuteDataTable("usp_PasswordSelect",
DAC.Parameter(CN_LoginId, Login)))
{
{
usr.Password = Convert.ToString(dt.Rows(0).Item(CN_Password));
}
}
return usr;
}
}
The first error I get is on this line usr.Password = Convert.ToString(dt.Rows(0).Item(CN_Password));. The error is “Error 1 ‘object’ does not contain a definition for ‘Password’ and no extension method ‘Password’ accepting a first argument of type ‘object’ could be found (are you missing a using directive or an assembly reference?)
At this point I am assuming the second error will go away when I fix the first one. So my question is how do I correctly set the property for this Object using the DataTable in C#?
Here’s how I’d write it:
Some notes:
Rows(0)isn’t correct – it should beRows[0].Userobject as aUser, and not as anobject. You’ll lose all visibility into it’s properties. You can also usevar, but if you’re learning C#, you may be better off explicitly declaring your variable types. It can make for duplicate declarations (e.g.User u = new User()) but at least you’ll see clearly what types your variables are.Item…just get it as an element in the row element you’re working with. That’s why I have the double array fordt.Rows[0][CN_Password]. Again, C# uses square brackets, not parens for accessing array elements._passwordfield and just used an automatic property forPassword. I didn’t see_passwordbeing used in your code and thought it would just clutter things up. Automatic properties have a backing field automatically created by the compiler, so you don’t have to keep track of the variable and the property. If you’re using a lot of properties, this can be a big time saver.