'New' Object won't specify while creating an object inside the class
'New' Object won't specify while creating an object inside the class
I am trying to create a class that will hold the object for the XML file. But it won't create a 'New' object. Here's my sample code below:
Private Sub CreateXml()
New XmlConfigSource().Save("myConfig.xml") 'this is the error.
End Sub
What will I do in order to make this code work? Thank you for answering. :)
What is the error? You can try enclosing the construction of the object in parentheses:
(New XmlConfigSource()).Save("myConfig.xml")– Chris Dunaway
Sep 4 '18 at 13:16
(New XmlConfigSource()).Save("myConfig.xml")
It won't hold anything, because once it is used it will be garbage collected. There is no lasting reference to the object. If you just want a class which can perform functions for you but not save any state, use a static class (
Module in VB.Net, like static class in C#)– djv
Sep 4 '18 at 14:17
Module
static class
2 Answers
2
You cannot begin a line of code with the New keyword. It's actually the only situation I've found the Call keyword to be genuinely useful. This will compile and do as you intend:
New
Call
Private Sub CreateXml()
Call New XmlConfigSource().Save("myConfig.xml")
End Sub
You would need parentheses.
Call (New XmlConfigSource()).Save("myConfig.xml")– djv
Sep 4 '18 at 14:15
Call (New XmlConfigSource()).Save("myConfig.xml")
@djv, no, you don't need parentheses. Test it for yourself. The compiler is clearly smart enough to know that there's only one way to interpret that expression and so does so. You do need to include the parentheses on the constructor call itself though, i.e. after the type. I usually don't include those parentheses on a constructor but they are required in this case.
– jmcilhinney
Sep 5 '18 at 0:06
Thanks for your answers guys. But I found some alternatives. This is what I'm doing:
Private Sub CreateXml()
Dim xmlConfig As String = "myConfig.xml"
Dim XML As XmlConfigSource = New XmlConfigSource()
XML.Save(xmlConfig)
End Sub
I hope this satisfies you all. Thank you for sharing some thoughts. :)
It seems like you only need a static class, because your
New XmlConfigSource isn't reused.– djv
Sep 5 '18 at 16:13
New XmlConfigSource
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You'll need to declare your object first. Dim xmlObj as <yourtype> ..
– Andrew Mortimer
Sep 4 '18 at 11:40