Hello everyone i'm new to c# language i was use vb.net, in below what is the error with this code and why, thank you
vb.net code
Class SplitString
Implements IEnumerable
Implements IEnumerator
Private currentPosition As Integer = 0
Private m_Sentence As String
Property Sentence() As String
Get
Return m_Sentence
End Get
Set(ByVal Value As String)
m_Sentence = Value
Me.Reset()
End Set
End Property
Public ReadOnly Property Current As Object Implements IEnumerator.Current
Get
Dim counter As Integer
Dim tmpLength As Integer = 0
For counter = Me.currentPosition To Me.Sentence.Length - 1
If Me.Sentence.Chars(counter) = " "c Then
Exit For
Else
tmpLength += 1
End If
Next
Current = Me.Sentence.Substring(Me.currentPosition, tmpLength) ' ok
Me.currentPosition += tmpLength + 1
End Get
End Property
Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext
If Me.currentPosition > Me.Sentence.Length - 1 Then
Me.Reset()
Return False
Else
Return True
End If
End Function
Public Sub Reset() Implements IEnumerator.Reset
Me.currentPosition = 0
End Sub
Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return Me
End Function
End Class
but when i try this code to c# i get Error
c# code
class SplitString:IEnumerable,IEnumerator
{
private int currentPosition = 0;
private string m_Sentence;
public string Sentence
{
get { return m_Sentence; }
set
{
m_Sentence = value;
this.Reset();
}
}
public IEnumerator GetEnumerator()
{
return this;
}
public object Current
{
get
{
int counter = 0;
int tmpLength = 0;
for (counter = this.currentPosition; counter <= this.Sentence.Length - 1; counter++)
{
if (this.Sentence[counter] == ' ')
{
break;
}
else
{
tmpLength += 1;
}
}
Current = this.Sentence.Substring(this.currentPosition, tmpLength); // Error
this.currentPosition += tmpLength + 1;
return functionReturnValue;
}
}
public bool MoveNext()
{
if (this.currentPosition > this.Sentence.Length-1)
{
this.Reset();
return false;
}
else
{
return true;
}
}
public void Reset()
{
this.currentPosition=0;
}
}
error: Property or indexer ‘Example.splitstring.current’ cannot ve assigned to – it is read only
This
Current = Me.Sentence.Substring(Me.currentPosition, tmpLength) ' ok
is the "old" VB way of setting a return value in a method without using the Return
keyword. In general, the following VB code
myMethodName = ...
...some other code...
End Function
can be rewritten as
Dim someTempVariable = ...
...some other code...
Return someTempVariable
End Function
(as long as some other code
does not exit the method).
The same is true for properties. Thus, we first rewrite your old VB code to new VB code:
...
Next
Dim returnValue = Me.Sentence.Substring(Me.currentPosition, tmpLength)
Me.currentPosition += tmpLength + 1
Return returnValue
End Get
and now the translation to C# should be obvious.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With