Create Logos

Using AI to Translate TypeScript to C#

Using AI to Translate TypeScript to C# blog article main image

A GPT-Assisted Approach

Introduction

Utilizing AI models like GPT for translating between programming languages offers several advantages:

  1. Simplifying Code Migration
    If an organization wishes to switch from an older programming language to a newer, more efficient one, AI can automate the translation process, significantly reducing the time and resources required for such a task.
  2. Enhancing Code Portability
    AI can aid in making a codebase more versatile by translating it to different languages. This can enable the software to run on more platforms or environments.
  3. Learning New Languages
    AI translation tools can help programmers learn new programming languages. By translating a familiar piece of code into a new language, the AI can provide practical examples that help programmers understand the syntax and structure of the new language.
  4. Boosting Productivity
    AI can translate code snippets almost instantly, allowing developers to prototype and experiment in their preferred language before translating the code into the language used by their team or project.
  5. Maintaining Coding Styles
    AI can learn to replicate specific coding styles during translation, helping to maintain consistency across different parts of a codebase.
  6. Reducing Errors
    AI models trained on vast amounts of code can be more reliable than manual translation, especially for complex or subtle language features, potentially resulting in fewer bugs.
  7. Helping with Legacy Code
    Legacy systems often use older programming languages. AI can help understand and translate this old code to modern languages, aiding in the modernization process.

While these benefits are promising, it's worth noting that automated translation between programming languages is a complex task and may not always be perfect, especially for complex programs. Human oversight will still be essential to ensure the translated code behaves as expected.

GPT Prompt

Convert the following code from Typescript to C#

import * as bcrypt from 'bcrypt';

class UserAuth {
  static validateEmail(email: string): boolean {
    let emailRegex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,}$/;
    return emailRegex.test(email);
  }
  
  static validatePassword(password: string): boolean {
    let passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$/;
    return passwordRegex.test(password);
  }

  static splitEmail(email: string): [string, string, string] {
    const [username, domain] = email.split('@');
    const domainParts = domain.split('.');
    const topLevelDomain = domainParts[domainParts.length - 1];

    return [username, domain, topLevelDomain];
  }
  
  static async hashPassword(password: string): Promise<string> {
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);
    return hashedPassword;
  }
  
  static async validateHash(password: string, hash: string): Promise<boolean> {
    return await bcrypt.compare(password, hash);
  }
}

Prompt Overview

In this case, the task was to convert TypeScript code into equivalent C# code, focusing on the key features used in the user authentication class. This involved translating not only the overall syntax but also understanding how key features like regular expressions, string splitting, async methods, and array initialisation work in both languages.

GPT Response

Here's how our TypeScript code would translate into C#:

using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using BCrypt.Net;

public class UserAuth {
    public static bool ValidateEmail(string email) {
        string emailRegex = @"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,}$";
        return Regex.IsMatch(email, emailRegex);
    }

    public static bool ValidatePassword(string password) {
        string passwordRegex = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$";
        return Regex.IsMatch(password, passwordRegex);
    }

    public static (string, string, string) SplitEmail(string email)
    {
        int atIndex = email.IndexOf('@');
        int lastDotIndex = email.LastIndexOf('.');
    
        if (atIndex == -1 || lastDotIndex == -1 || atIndex > lastDotIndex)
        {
            throw new ArgumentException("Invalid email format");
        }
    
        string username = email.Substring(0, atIndex);
        string domain = email.Substring(atIndex + 1);
        string topLevelDomain = email.Substring(lastDotIndex + 1);
    
        return (username, domain, topLevelDomain);
    }

    public static async Task<string> HashPassword(string password) {
        string salt = BCrypt.Net.BCrypt.GenerateSalt(10);
        string hashedPassword = BCrypt.Net.BCrypt.HashPassword(password, salt);
        return hashedPassword;
    }

    public static async Task<bool> ValidateHash(string password, string hash) {
        return BCrypt.Net.BCrypt.Verify(password, hash);
    }
}

GPT Response Overview

The C# equivalent code maintains the structure of the original TypeScript code, using static methods within a class. However, there are a few key differences:

  1. Regular Expressions: In C#, we use the Regex class from the System.Text.RegularExpressions namespace to handle regular expressions.
  2. Splitting Strings: The string.Split() function in C# is equivalent to split() in TypeScript.
  3. Asynchronous Functions: In C#, we use the async keyword and Task to define asynchronous methods. But the BCrypt methods used here are synchronous in C#, unlike their counterparts in JavaScript.
  4. Array Initialization: When returning an array in C#, we use the new keyword to initialize it.

Benefits and Conclusion

The ability to translate code between languages is a valuable skill in software development. It helps you understand the strengths and limitations of different languages and broadens your potential toolset.

While C# and TypeScript have different features and syntax, they both can effectively handle tasks such as user authentication. This example has shown how similar functionality can be implemented in these two languages, providing a stepping stone for further exploration.

Was This Helpful?

If you found this blog post helpful, feel free to check out our other blog posts on using AI in software development at the Logobean Blog!

Blog CTA

Get Started For Free. No Signup Required.

1. Get started

Add your business name to instantly generate an endless selection of logos and brands.

Icon AI business name & slogan generator
Icon Select a business or general logo theme
Icon Select a logo name layout (for 2+ word names)
Icon Generate unlimited logos in seconds
Icon No sign up required
Start Logobean Logo Maker
Logobean logo maker get started
Logobean logo maker select styles live preview favorite

2. Select styles, live preview and favorite your logos

Select your logo styles to refine the generated logos, click any logo to view it in the live previews & logo style guide and favorite the logos that you love.

Icon Select styles to refine your generated logos
Icon Filter logo layouts, icons, colors, fonts & more
Icon Revolutionary & interactive logo previews
Icon Live & interactive logo style guide
Icon Save logos that you love to your favorites
Start Logobean Logo Maker

3. Edit and perfect your logo

Edit any logo to perfection using our intuitive logo and rich text editors.

Icon Intuitive logo editors for every logo layout
Icon Rich text editors for your name and slogan
Icon Icon, color and font selectors
Icon Smart icon coloring
Icon Live preview your logo whilst editing
Start Logobean Logo Maker
Logobean logo maker edit logo editor
Logobean logo maker select styles live preview favorite

4. Download your logo files & more

Once you've found the perfect logo, download and use your logo package instantly!

Icon High quality PNG & SVG logo files
Icon 100+ on-brand designs
Icon Ready-to-upload social media profile & cover images
Icon Brand color palette
Icon Manage your logos, brand and downloads on-going
Start Logobean Logo Maker

Ready to get started?