0

I'm getting an error with the optional argument, it says "Constant expression is required"

How I can resolve the problem?

Private Function Write_Text_To_File(ByVal Text_File As String, _
                              ByVal Text As String, _
                              ByVal Append_Text As Boolean, _
                              Optional Encoding As System.Text.Encoding = System.Text.Encoding.Default) As Boolean

    Try : Using TextFile As New IO.StreamWriter(Text_File, Append_Text, Encoding) : TextFile.WriteLine(Text) : End Using
        Return True
    Catch ex As Exception
        'Return False
        Throw New Exception(ex.Message)
    End Try

End Function

UPDATE:

Solution

#Region " Write Text to File "

' [ Write Text to File Function ]
'
' // By Elektro H@cker
'
' Examples :
'
' Write_Text_To_File("C:\Test.txt", "Text", False)
' Write_Text_To_File("C:\Test.txt", "Text", True, System.Text.Encoding.UTF8)

Private Function Write_Text_To_File(ByVal Text_File As String, _
                              ByVal Text As String, _
                              ByVal Append_Text As Boolean, _
                              Optional Encoding As System.Text.Encoding = Nothing) As Boolean
    Try
        If Encoding Is Nothing Then Encoding = System.Text.Encoding.Default
        Using TextFile As New IO.StreamWriter(Text_File, Append_Text, Encoding) : TextFile.WriteLine(Text) : End Using
        Return True
    Catch ex As Exception
        'Return False
        Throw New Exception(ex.Message)
    End Try

End Function

#End Region
ElektroStudios
  • 19,105
  • 33
  • 200
  • 417

1 Answers1

2

How I can resolve the problem?

Well, you simply can't using Encoding.Default as a default parameter value.

What you could do is use Nothing as a default parameter value, and simply have:

If Encoding Is Nothing Then
    Encoding = System.Text.Encoding.Default
End If

This does mean you can't use Nothing for a different meaning, mind you.

Another alternative would be to just use overloading - provide one version without the encoding parameter which just called the version with the encoding parameter, passing in Encoding.Default.

Two other points to note:

  • Your parameter names don't follow .NET naming conventions; they should be camelCased
  • Encoding.Default is generally a bad default to use (and poorly named). Pretty much everything in .NET actually uses Encoding.UTF8 as the default encoding if you don't specify one; I'd urge you to follow suit.
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Can you give me a example of what means camel casing? I don't speak english and can't translate that word (Google translate it literally as a Camel...) – ElektroStudios Apr 16 '13 at 08:40
  • @ElektroHacker: Did you try a simple search? http://en.wikipedia.org/wiki/CamelCase (And follow the linked documentation for naming conventions.) – Jon Skeet Apr 16 '13 at 08:43