okay guys, i'm new in C# programming, today i was trying to create constructor which will be like a String constructor but the problem is that i have to return the result after i use it, but as i know constructora can't have return type and can't be static
using System;
class StringA {
public StringA(char x, int y) {
string res = "";
string ConvertedChar = Convert.ToString(x);
for (int i = 0; i < y; i++) {
res += ConvertedChar;
}
// How to return string res?
}
}
class MainClass {
static void Main() {
Console.WriteLine(new StringA('B', 15));
}
}
What you could do is to override the ToString() Method of your class StringA.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(new StringA('B', 15));
Console.Read();
}
}
class StringA
{
string res = "";
public StringA(char x, int y)
{
string ConvertedChar = Convert.ToString(x);
for (int i = 0; i < y; i++)
{
res += ConvertedChar;
}
}
public override string ToString()
{
return res;
}
}
Are you looking for a static factory method?
public static string CreateRepeatedString(char x, int y) {
return new string(x, y);
}
You could use keyword out
in following way:
class StringA
{
public StringA(char x, int y, out string res)
{
res = "";
string ConvertedChar = Convert.ToString(x);
for (int i = 0; i < y; i++)
{
res += ConvertedChar;
}
// or even shorter
// res = new string(x, y);
}
}
Then you can pass some string to constrctor and get it's value changed in constructor. Then you can use it:
class MainClass
{
static void Main()
{
string res;
Console.WriteLine(new StringA('B', 15, out res));
}
}
Perhaps you can create a public accessor for your class, or would you rather need a static factory method as @Joey stated in his answer ?
See below example:
using System;
namespace YourNamespace {
class StringA {
private string privateVal = "";
public string PublicVal {
get {
return this.privateVal;
}
set {
this.privateVal = value;
}
}
public StringA(char x, int y) {
string res = "";
string ConvertedChar = Convert.ToString(x);
for (int i = 0; i < y; i++) {
res += ConvertedChar;
}
// How to return string res?
this.privateVal = res; //assign res to your accessor
}
}
class MainClass {
static void Main() {
//then you can access the public property
Console.WriteLine(new StringA('B', 15).PublicVal);
}
}
}
Besides the above answers, you can also add an implicit operator
class StringA
{
private readonly string instance;
public StringA(char x, int y)
{
string res = "";
string ConvertedChar = Convert.ToString(x);
for (int i = 0; i<y; i++)
{
res += ConvertedChar;
}
this.instance = res;
}
public static implicit operator string(StringA d) => d.instance;
}
This can then be used as:
string str = new StringA('x', 10);
Console.WriteLine(new StringA('y',100));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.