Reputation: 31
var
UserName, NickName, UserID: string;
begin
with TStringList.Create do
begin
CommaText := 'ali,veli,4950';
UserName := x[0]; //what is x ? (x is Tstringlist.create)
NickName := x[1];
UserID := x[2];
end;
end;
If I use the below code, it works. But I don't want to declare a variable. Can I use it with any variable?
In the with
statement, how can I use it?
var
tsl: TStringList;
begin
tsl := TStringlist.Create;
with tsl do
begin
CommaText := 'ali,veli,4950';
UserName := tsl[0];
NickName := tsl[1];
UserID := tsl[2];
end;
end;
Upvotes: 2
Views: 251
Reputation: 595712
When an object is created directly in a with
statement, there is no syntax to refer to that object (unless it provides a member that refers to itself, which is very rare), so you typically must use a variable, as your bottom code does.
Also, both codes are leaking the TStringList
object, as you are not calling Free()
on it when you are done using it.
That being said, in this particular example, the []
operator is just shorthand for accessing the TStrings.Strings[]
default property, which you can access without needing a variable to the created TStringList
object, just like you are doing with the TStrings.CommaText
property, eg:
var
UserName, NickName, UserID: string;
Begin
with TStringList.Create do
try
CommaText := 'ali,veli,4950';
UserName := Strings[0];
NickName := Strings[1];
UserID := Strings[2];
finally
Free;
end;
end;
Upvotes: 7